如何使用 Selenium Webdriver 跨浏览器点击输入类型为 file 的按钮?
seleniumautomation testingtesting tools更新于 2026/2/11 16:37:17
我们可以使用 Selenium Webdriver 跨浏览器点击带有 <input type= file> 的按钮。首先,我们需要借助 xpath 或 css 等定位器识别元素,然后调用 sendKeys() 方法,并传入要上传的文件路径。

让我们看一下输入类型为 file 的元素的 html 代码。该元素在屏幕上的对应表示形式应为。

要使用此元素,我们首先需要与"浏览"按钮交互,并且要上传的文件的路径也应有效。
示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class TypeFile{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url ="https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// 识别元素
WebElement l=driver.findElement(By.cssSelector("input[type='file']"));
// 使用 sendkeys() 传递的文件路径
l.sendKeys("C:\Users\ghs6kor\Pictures\Desert.jpg");
driver.quit();
}
}
输出


