Selenium sendKeys仅为输入追加文件[类型=文件多个]

问题描述

我无法使用硒清除隐藏的多个文件输入。

HTML来源

<input type="file" multiple style="display: none"/>

webElement.sendKeys(file1.absolutePath); // ?? file1 added
webElement.sendKeys(file2.absolutePath); // ⚠ appends file2
webElement.sendKeys(file3.absolutePath); // ⚠ appends file3
/// and so on

文件只是连续追加到输入中,没有明显的清除方法。我已经显示了用于调试目的的input元素,并且所有文件都已放入字段中。

Files just appended to input

我尝试使用WebElement.clear()sendKeys(Keys.BACK_SPACE)和其他几个。没有人可以使用隐藏的输入元素。

解决方法

只需抓住标签并使用 driver.execute 即可更改该标签的值。

js = "document.getElement(By.tagName("input")).value = "+file2.absolutePath; 
driver.execute_script(js).