Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium WebDriver clicking on hidden element

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?

like image 672
Chun ping Wang Avatar asked Aug 20 '12 15:08

Chun ping Wang


People also ask

Can Selenium click on hidden element?

Selenium by default cannot handle hidden elements and throws ElementNotVisibleException while working with them. Javascript Executor is used to handle hidden elements on the page. Selenium runs the Javascript commands with the executeScript method.

How do I get hidden text elements?

WebElement hiddenDiv = seleniumDriver. findElement(By.id("hidden_div")); String n = hiddenDiv. getText(); // does not work (returns "" as expected) String script = "return arguments[0]. innerText"; n = (String) ((JavascriptExecutor) driver).

How do you handle an element not visible exception?

First Solution: Try to write unique XPATH that matches with a single element only. Second Solution: Use Explicit wait feature of Selenium and wait till the element is not visible. Once it is visible then you can perform your operations.


1 Answers

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.

like image 170
Ashwin Prabhu Avatar answered Sep 28 '22 01:09

Ashwin Prabhu