Selenium Webdriver - 点击隐藏元素 [英] Selenium Webdriver - click on hidden elements

查看:76
本文介绍了Selenium Webdriver - 点击隐藏元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to automate upload file functionality in Google Drive.

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

The element used to pass parameters is hidden with height - 0px.

任何用户操作都不会使该元素可见.所以我需要一种解决方法来在元素不可见时点击它.

None of the user actions would make this element visible. So I need a work around to click on the element while it is not visible.

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

上述元素的 xpath 是 -

The xpath for the above element is -

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

我正在使用

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

异常 -

org.openqa.selenium.ElementNotVisibleException

  • 元素当前不可见,因此可能无法与之交互.
  • 我尝试过使用 JavascriptExecutor.但是找不到确切的语法.

    I have tried using JavascriptExecutor. But unable to find the exact syntax.

    推荐答案

    试试这个:

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

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

    The above bunch would change the visibility of your file input control. You can then proceed with the usual steps for file upload like:

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

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

    Be aware, by changing the visibility of an input field you are meddling with the application under test. Injecting scripts to alter behavior is intrusive and not recommended in tests.

    这篇关于Selenium Webdriver - 点击隐藏元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆