24

我正在尝试在 Google Drive 中自动上传文件功能。

用于传递参数的元素被隐藏,高度为 0px。

任何用户操作都不会使该元素可见。因此,我需要解决方法以在不可见时单击该元素。

<input type="file" style="height: 0px; visibility: hidden; position: absolute; width: 340px; font-size: inherit;" multiple=""/>

上述元素的 xpath 是 -

//*[@class='goog-menu goog-menu-vertical uploadmenu density-tiny']/input

我在用

WebDriver.findElement(By.xpath(<xpath>).sendKeys(<uploadFile>)

例外 -

org.openqa.selenium.ElementNotVisibleException
  • 元素当前不可见,因此可能无法与之交互。

我尝试过使用 JavascriptExecutor。但无法找到确切的语法。

4

5 回答 5

24

试试这个:

WebElement elem = yourWebDriverInstance.findElement(By.xpath("//*[@class='goog-menu goog-menu-vertical uploadmenu density-tiny']/input"));
String js = "arguments[0].style.height='auto'; arguments[0].style.visibility='visible';";

((JavascriptExecutor) yourWebDriverInstance).executeScript(js, elem);

上面的一堆会改变你的文件输入控件的可见性。然后,您可以继续执行文件上传的常规步骤,例如:

elem.sendKeys("<LOCAL FILE PATH>"); 

请注意,通过更改输入字段的可见性,您正在干预被测应用程序。注入脚本来改变行为是侵入性的,不建议在测试中使用。

于 2012-09-11T06:50:01.247 回答
14

简单的解决方案:

WebElement tmpElement = driver.finElement(ElementLocator);
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", tmpElement);
于 2014-05-28T02:53:42.693 回答
2

试试这个示例代码:

JavascriptExecutor executor= (JavascriptExecutor)driver;
executor.executeScript("document.getElementById('ID').style.display='block';");
Select select = new Select(driver.findElement(By.id("ID")));
select.selectByVisibleText("value");
Thread.sleep(6000);

通过使用 java 脚本执行器并使元素可见,然后通过 ID 单击元素。希望它有帮助..

于 2014-01-31T08:57:00.930 回答
1

试试这个:

WebElement elem = yourWebDriverInstance.findElement(
   By.cssSelector(".uploadmenu > input"));
String js = 
  "arguments[0].style.height='auto'; arguments[0].style.visibility='visible';";
((JavascriptExecutor) yourWebDriverInstance).executeScript(js, elem);

在这里,我用 CSS 选择器替换了 XPath。让我知道上述脚本是否有效。

于 2014-04-09T09:47:36.253 回答
1

您可以尝试以下方法:

((JavascriptExecutor)driver).executeScript("$('.goog-menu.uploadmenu > input').click();");
于 2014-04-09T10:16:52.073 回答