Selenium WebDriver 如何将文件上传到浏览器?
seleniumautomation testingtesting tools更新于 2026/2/12 11:37:17
我们可以借助 Selenium WebDriver 将文件上传到浏览器。这是通过元素上的 sendKeys() 方法完成的,该方法通过指定要上传文件的路径来选择文件。

在使用文件上传功能时,我们需要点击"浏览"按钮。对于属性类型值为"文件"的元素,WebDriver 会处理此操作。此外,要上传的文件路径必须正确。

示例
代码实现。
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 FileUpld{
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.xpath("//input[@name='photo']"));
// 带有文件路径的文件选择字段
l.sendKeys("C:\Users\ghs6kor\Pictures\Tulips.jpg");
driver.quit();
}
}
输出


