使用硒上传文件时遇到问题

时间:2018-11-09 03:10:47

标签: java selenium-webdriver

我正在学习在网站中自动执行procress。我选择http://logos.iti.gr/logos/作为要自动化的网站。使用“上传图像”按钮上传图像文件时遇到问题,因为单击该按钮时似乎转换为文本字段。

我遵循的其他教程获得了文本字段的ID,并使用sendkeys发送路径,因为它们确实具有单独的文本字段和上载按钮键。

这是我尝试过的代码:

 driver.get("http://logos.iti.gr/logos/");
 driver.findElement(By.id("fileToUpload")).clear();
 System.out.println("Cleared");              
 driver.findElement(By.id("fileToUpload")).sendKeys("/home/test.jpg");

我不知道问题是什么。它只是得到IPDL协议错误:处理程序返回了错误代码!

org.openqa.selenium.ElementNotInteractableException: Element <input id="fileToUpload" class="input_file" name="fileToUpload" type="file"> could not be scrolled into view
Build info: version: '3.141.5', revision: 'd54ebd709a', time: '2018-11-06T11:42:16'

2 个答案:

答案 0 :(得分:1)

您得到ElementNotInteractableException-抛出该错误以表明尽管DOM上存在一个元素,但该元素处于无法与之交互的状态。对于您而言,它的发生是因为元素的样式为display:none。基本上,硒(以及真实用户)不能与不可见元素进行交互。您需要在第一个位置使元素可见,然后继续。

    driver.get("http://logos.iti.gr/logos/");
    WebElement el = driver.findElement(By.id("fileToUpload"));
    System.out.println("Making element visible");  
    ((JavascriptExecutor)driver).executeScript("arguments[0].style.display = 'block';", el);
    el.clear();
    System.out.println("Cleared");              
    el.sendKeys("/home/test.jpg");

顺便说一下,这里是默认的元素样式(您可以在浏览器开发工具中看到它)。注意display:none。当您将值更改为block时,不要混淆您实际上在屏幕上看不到任何更改,因为元素的宽度和高度很小。

.input_file {
    width: 0.1px;
    height: 0.1px;
    opacity: 0;
    overflow: hidden;
    position: absolute;
    z-index: -1;
    display: none;
}

答案 1 :(得分:0)

尝试更新客户端和Firefox。希望那能解决这个问题。

我从未遇到文件上传的任何问题,直到网页在单击图像上传时授权对话框。我正在使用最新版本的ChromeDriver和Chrome。

如果可能的话,您也可以切换到ChromeDriver,因为根据我的经验,这两人可以无缝地一起工作! :)