ISTQB Certified Software Test Engineer

Tuesday, April 24, 2012

Handling Element not visible exception in Selenium


While working with Selenium Web driver in your project,there will be some scenarios like handling Smart Menus(Drop down menus),hidden buttons,hidden links etc...
Some times using wait's will solve the problem of handling hidden elements,but not every time.

For example if we are using drop down menu,when we click on Main menu,the drop down will be populated.When we change the mouse position the drop down will close.In such scenarios it will be difficult to click on sub menu.

This can be handled by using JavaScriptExecutor Class of Web driver.Using this class we need to change the CSS property of that web element(By default this element is invisble)as below.
JavascriptExecutor js=(JavascriptExecutor)driver; js.executeScript("$('"+CssSelector+"').css({'display':'block'});");

Example:
<span class="main">Outer Span
<span>Inner Span</span>
<ul style="display:none">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</span>
The list in the inner span is invisible,assume that it will be visible when we place mouse on the outer span. This scenario is difficult to handle using web driver,because when we change mouse position the list may go invisble. This case will be handled in web driver by using the following piece of code.

driver.findElement(By.ClassName("main")).click();
//click on Span,then change CSS property of UL using JavaScript Executor
JavascriptExecutor js=(JavascriptExecutor)driver;
js.executeScript("$('span.main ul').css({'display':'block'});");

2 comments: