「Selenium」- 文件上传 @20210311

Selenium文件上传
本文介绍如何使用Selenium进行文件上传,特别关注FirefoxDriver和ChromeDriver的使用方法,并解决了因文件系统隔离导致的上传失败问题。

问题描述

我们需要使用 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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值