Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Webdriver - click on hidden elements

Tags:

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

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=""/> 

The xpath for the above element is -

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

I am using

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

Exception -

org.openqa.selenium.ElementNotVisibleException 
  • Element is not currently visible and so may not be interacted with.

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

like image 271
praneel Avatar asked Sep 11 '12 05:09

praneel


People also ask

How do I click hidden elements in Selenium Webdriver?

In case an element is a part of the form tag, it can be hidden by setting the attribute type to the value hidden. 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.

How do you show hidden text in Selenium?

In some cases, one may find it useful to get the hidden text, which can be retrieved from element's textContent , innerText or innerHTML attribute, by calling element. attribute('attributeName') . element. getAttribute("textContent") worked for me.


2 Answers

Try this:

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.

like image 181
Ashwin Prabhu Avatar answered Sep 24 '22 17:09

Ashwin Prabhu


Simple solution:

WebElement tmpElement = driver.finElement(ElementLocator); JavascriptExecutor executor = (JavascriptExecutor)driver; executor.executeScript("arguments[0].click();", tmpElement); 
like image 25
Karthikeyan Avatar answered Sep 23 '22 17:09

Karthikeyan