Selenium 4.4.0多文件上传异常及换行分隔符失效求助
Selenium v4.4.0 多文件上传重复问题排查与解决
问题现象
- 批量上传文件时出现重复上传异常:第一个文件被上传3次,第二个2次,第三个1次(上传第二个文件时附带第一个,上传第三个时附带前两个)
- 单个文件上传(filepaths列表仅含一个元素)功能正常
- 原通过「进入上传页面→传第一个文件→保存返回→再传第二个」的逐个上传规避方案,无法适用于当前场景
- 尝试用
\n作为文件路径分隔符,未解决问题
相关代码
ApplyFilesPO.uploadFile 方法
public ApplyFilesPO uploadFile(@NotNull List<String> filepaths) { String filepath = String.join("\n", filepaths); uploadFilePO.uploadFile(filepath, fileInput, progressBar); return this; // 列表元素多于1时失效 }
UploadFilePO.uploadFile 方法
public void uploadFile(String filename, By input, By progressBar) { File file = new File(Objects .requireNonNull(getClass().getClassLoader().getResource(filename)) .getFile()); getExistingElement(input).sendKeys(file.toString()); waitForElementToDisappear(progressBar); }
辅助方法
getExistingElement
protected final WebElement getExistingElement(By locator) { return wait.until(ExpectedConditions.presenceOfElementLocated(locator)); }
waitForElementToDisappear
protected final <T> void waitForElementToDisappear(T locator) { wait.until(isBy(locator) ? ExpectedConditions.invisibilityOfElementLocated((By) locator) : ExpectedConditions.invisibilityOf((WebElement) locator)); }
补充说明
上传输入框为2px×0px的隐藏元素,需点击按钮唤起文件选择窗口
问题分析
核心错误在于多文件路径的处理逻辑完全错误:
- 错误地将多个资源文件名用
\n拼接后,当成单个资源路径去加载——classpath下不存在包含\n的资源文件,此操作本身无效 - 未正确生成多文件上传所需的「绝对路径拼接字符串」,导致
sendKeys传入的内容不符合Selenium多文件上传的规范
解决方案
修正代码逻辑
1. 修改ApplyFilesPO.uploadFile 方法
遍历每个资源文件名,生成对应绝对路径后再用\n拼接:
import java.util.stream.Collectors; public ApplyFilesPO uploadFile(@NotNull List<String> filepaths) { String multiFilePaths = filepaths.stream() .map(resourceName -> { File file = new File(Objects.requireNonNull(getClass().getClassLoader().getResource(resourceName)).getFile()); return file.getAbsolutePath(); }) .collect(Collectors.joining("\n")); uploadFilePO.uploadFile(multiFilePaths, fileInput, progressBar); return this; }
2. 修改UploadFilePO.uploadFile 方法
直接将拼接好的多文件绝对路径字符串传入sendKeys,无需再加载资源:
public void uploadFile(String multiFilePaths, By input, By progressBar) { getExistingElement(input).sendKeys(multiFilePaths); waitForElementToDisappear(progressBar); }
关键验证点
- 确认页面上传输入框带有
multiple属性:<input type="file" multiple>,这是多文件上传的必要前提 - 确保所有文件路径无权限问题,文件本身存在且可访问
- 避免重复定位上传输入框,确保每次操作的是同一个元素
内容的提问来源于stack exchange,提问作者hetacz
相关产品推荐
相关产品推荐

