Selenium WebDriver点击Choose File按钮无法打开文件上传窗口
问题根因
- Chrome高版本默认拦截Selenium主动触发
<input type="file">元素的点击事件唤起系统原生弹窗,该类弹窗不属于浏览器DOM管控范围,Selenium原生点击逻辑对此类交互存在默认限制。 - 你的代码存在两处语法/配置错误:
- ChromeDriver路径配置错误,当前配置的
C:\Users\shash\eclipse-wo是工作目录,不是chromedriver.exe的完整路径,驱动异常会导致交互逻辑失效 WebElement uploadPhotoBtn = driver.findElement(By.xpath("//input[@id='file-upload']"))行末缺少分号,存在编译错误
- ChromeDriver路径配置错误,当前配置的
解决方案
方案1:官方推荐无弹窗上传(稳定性最高)
Selenium针对文件上传场景原生支持直接向type=file的input元素传入本地文件路径,无需唤起文件选择窗口,将你代码的最后一行uploadPhotoBtn.click();替换为以下代码即可:
// 路径替换为你要上传的本地文件完整绝对路径,注意Java字符串中反斜杠需要转义为双反斜杠 uploadPhotoBtn.sendKeys("C:\\Users\\shash\\Desktop\\测试文件.png");
执行完成后直接点击提交按钮即可完成上传流程。
方案2:需要唤起系统文件选择弹窗的处理方式
如果业务场景必须触发弹窗,需要给ChromeDriver添加启动参数放开弹窗限制,调整后的完整代码如下:
// 替换为你本地chromedriver.exe的完整路径 System.setProperty("webdriver.chrome.driver","C:\\Users\\shash\\eclipse-wo\\chromedriver.exe"); ChromeOptions options = new ChromeOptions(); // 放开文件访问限制,允许触发文件选择弹窗 options.addArguments("--allow-file-access-from-files"); options.addArguments("--disable-web-security"); WebDriver driver=new ChromeDriver(options); driver.navigate().to("http://the-internet.herokuapp.com/upload"); Thread.sleep(5000); WebElement uploadPhotoBtn = driver.findElement(By.xpath("//input[@id='file-upload']")); uploadPhotoBtn.click();
内容的提问来源于stack exchange,提问作者Snk2611uk
相关产品推荐
相关产品推荐

