Selenium Webdriver - 单击隐藏的元素

时间:2012-09-11 05:02:53

标签: selenium webdriver hidden-field

我正在尝试自动化Google云端硬盘中的上传文件功能。

用于传递参数的元素隐藏为height - 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。但无法找到确切的语法。

5 个答案:

答案 0 :(得分:21)

试试这个:

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>"); 

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

答案 1 :(得分:10)

简单的解决方案:

WebElement tmpElement = driver.finElement(ElementLocator);
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", tmpElement);

答案 2 :(得分: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);

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

答案 3 :(得分: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 Selector替换了XPath。让我知道上面的脚本是否有效。

答案 4 :(得分:1)

您可以试试以下内容:

((JavascriptExecutor)driver).executeScript("$('.goog-menu.uploadmenu > input').click();");
相关问题