问题描述
我们需要使用 Selenium 进行文件上传,以完成功能测试任务。
但是,在尝试多种方法后,都会遇到如下错误:
org.openqa.selenium.InvalidArgumentException: invalid argument: File not found : xxxxxxx
该笔记将记录:在 Selenium 中,如何实现文件上传,以及相关问题处理。
解决方案
方法一、使用 FirefoxDriver 上传
我们没有使用 FirefoxDriver 上传的方法,这里只是记录这种做法:
import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; public class PG9 { public static void main(String[] args) { System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe"); String baseUrl = "http://demo.guru99.com/test/upload/"; WebDriver driver = new FirefoxDriver(); driver.get(baseUrl); WebElement uploadElement = driver.findElement(By.id("uploadfile_0")); uploadElement.sendKeys("C:\\newhtml.html"); driver.findElement(By.id("terms")).click(); driver.findElement(By.name("send")).click(); } }
在 Chromium 中,该方法无效,会产生最开始我们提到的错误(无法找到文件),不能直接使用 sendKeys() 方法。 —— # 03/07/2021 参考“补充说明”部分
方法二、使用 ChromeDriver 上传
public void uploadFile(){ ... webDriver.setFileDetector(new LocalFileDetector()); ... input.sendKeys(filePath); ... }
为了简单演示,这里之粘贴关键代码的两行代码
补充说明
org.openqa.selenium.InvalidArgumentException: invalid argument: File not found : xxxxxxx
# 03/07/2021 后来,我们恍然大悟,突然想起来 Ubuntu 20.04 的 Chromium 是通过 snap 安装的,它的文件系统是隔离的、受限的,不是主机的根文件系统。而我们的被上传文件保存在主机中的其他目录,这对于通过 snap 安装的 Chromium 是不可见的。所以,才会提示无法找到文件。
解决方法:在 Ubuntu 20.04 中,需要使用 snap 才能安装 Chromium 浏览器(或许是我们没有找到方法)。因此,我们直接放弃使用 Chromium 浏览器,改用 Google Chrome 浏览器:
1)首先,安装 Google Chrome 浏览器,安装 ChromeDriver 驱动;
相关文章
「Selenium」- 在页面中,点击按钮(或元素)
参考文献
How to Upload & Download a File using Selenium Webdriver
protractor - invalid argument: File not found error when trying to upload a file - Stack Overflow
java - Selenium upload file: file not found [docker] - Stack Overflow
How to upload a file by transfering the file from the local machine to the remote web server using Selenium Grid