问题描述
我们需要使用 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(); } }
方法二、使用 ChromeDriver 上传
为了简单演示,这里之粘贴关键代码的两行代码:
public void uploadFile(){ ... webDriver.setFileDetector(new LocalFileDetector()); ... input.sendKeys(filePath); ... }
Q:使用 Chrome 或 Chromium 浏览器遇到 File not found 错误,
A:可能是因为 Chromium 是通过 snap 安装,其文件系统隔离导致该问题。
常见问题
… org.openqa.selenium.InvalidArgumentException: invalid argument: File not found …
在使用 Selenium 进行文件上传(Uploading Files)的时候,会提示如下错误:
org.openqa.selenium.InvalidArgumentException: invalid argument: File not found : xxxxxxx
该问题与特定环境相关,我们实在 Ubuntu 20.04 中遇到该问题。
# 03/07/2021 后来,我们恍然大悟,突然想起来 Ubuntu 20.04 的 Chromium 是通过 snap 安装的,它的文件系统是隔离的、受限的,不能随意访问主机的根文件系统。而我们的被上传文件保存在主机中的其他目录,这对于通过 snap 安装的 Chromium 是不可见的。所以,才会提示无法找到文件。
在 Ubuntu 20.04 中,需要使用 snap 才能安装 Chromium 浏览器。当然也能够通过 deb 方法来安装,但是繁琐不说,而且日后或许会带来其他问题(我们并不清楚 Ubuntu 以后会怎么变化,采取与官方默认行为不同的做法,日后可能带来麻烦)。
因此,我们直接放弃使用 Chromium 浏览器,改用 Google Chrome 浏览器:
1)首先,卸载 snap 服务(虽与解决问题无关,这是为了避免日后的其他麻烦);
2)然后,安装 Google Chrome 浏览器,安装 ChromeDriver 驱动;
参考文献
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