Selenium WebDriver clicking on hidden element

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 21:50:28

问题


Hi I would like to know how to click on hidden element and/or disable element by using Selenium WebDriver.

I know with selenium 1 I can do this as below:

selenium.click(id="idOfHiddenField");

and this would work, but with selenium 2 (WebDriver), this doesn't. I do not want to use jquery to enable or show hidden fields , or JavaScript. This is because most of the test are using xpath.

Or do I just have to stay with old selenium which allows you to click on hidden fields?


回答1:


There is a easier way to work around the problem using JavascriptExecutor.

For example:

document.getElementsByClassName('post-tag')[0].click();

The above javascript would click on the "Selenium" tag on the top right of this page (next to your question), even if it were hidden (hypothetically).

All you need to do is issue this JS instruction via the JavascriptExecutor interface like so:

(JavascriptExecutor(webdriver)).executeScript("document.getElementsByClassName('post-tag')[0].click();");

This would use the JS sandbox and synthetic click event to perform the click action. Although it defeats the purpose of WebDriver user activity simulation, you can use it in niche scenarios like in your case to good effect.




回答2:


there is one answer but multiple suggestions:

Answer: use selenium backed driver to click on the hidden element using something like

Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);
selenium.clickAt("xpath=//area[@alt='Mercury']", clickPoint);

Suggestion 1: to create fake data specially if there's a lot to be created and you are looking for FOSS go for JMeter.

Suggestion2: to check javascript turned off disable javascript in the firefox instance itself e.g.

DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setJavascriptEnabled(false);



回答3:


It may not fit your needs, but another solution for some might be to alter the CSS for hiding an element.

Whilst Selenium won't find an element with display: none; it will find an element with the following:

.hide {
    position: absolute;
    top: -99em;
    left: -99em;
}

Then rather than using jQuery.show/hide/toggle in your app, you would use jQuery.toggleClass('hide', true/false/unset_to_toggle).



来源:https://stackoverflow.com/questions/12040615/selenium-webdriver-clicking-on-hidden-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!