【问题标题】:Selenium Webdriver - click on hidden elementsSelenium Webdriver - 点击隐藏元素
【发布时间】:2012-09-03 23:45:02
【问题描述】:

我正在尝试在 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。但是找不到确切的语法。

【问题讨论】:

  • 看一下 HTML,Google Drive 只是一个表单吗?如果是这样,请不要使用 Selenium,只需编写一个脚本来发布包含您指定数据的表单。

标签: selenium webdriver hidden-field


【解决方案1】:

试试这个:

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

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

【讨论】:

  • 这对 Appium Android 平台中可用的隐藏元素也有效吗?
【解决方案2】:

简单的解决方案:

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

【讨论】:

    【解决方案3】:

    试试这个示例代码:

    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单击元素。希望对你有帮助。。

    【讨论】:

    • 为什么需要线程休眠? executeScript 应该是同步的
    【解决方案4】:

    您可以尝试以下方法:

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

    【讨论】:

      【解决方案5】:

      试试这个:

      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。让我知道上述脚本是否有效。

      【讨论】:

        猜你喜欢
        • 2012-08-15
        • 2016-01-07
        • 1970-01-01
        • 1970-01-01
        • 2014-04-02
        • 2020-01-29
        • 2013-07-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多