Pages

Search This Blog

Tuesday, May 18, 2010

How to identify dynamic element in selenium

Many web sites create dynamic element on their web pages where Ids of the elements gets generated dynamically. Each time id gets generated differently. So to handle this situation we use some JavaScript functions.

starts-with

if your dynamic element's ids have the format <button id="continue-12345" /> where 12345 is a dynamic number you could use the following

XPath: //button[starts-with(@id, 'continue-')]  

contains

Sometimes an element gets identfied by a value that could be surrounded by other text, then contains function can be used.
To demonstrate, the element <input class="top suggest business"> can be located based on the ‘suggest’ class without having to couple it with the ‘top’ and ‘business’ classes using the following

XPath: //input[contains(@class, 'suggest')].

How to use Css instead of Xpath in selenium

Sometimes selenium gets confused to identify an element on the web page because more than one elements have the same name and ids so to handle this situation we instructs selenium to identify the object using CSS instead of Xpath.


<tr>
<td>open</td>
<td>http://economictimes.indiatimes.com/</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>css=input[style='width: 120px; font-size: 12px;']</td>
<td>Business</td>
</tr>

In selenium RC you can use below code

selenium.open("http://economictimes.indiatimes.com/");

selenium.type("css=input[style='width: 120px; font-size: 12px;']", "Business");

There is another way to use css instead of Xpath

Try below code for clicking on search button on www.google.com


<tr>
<td>type</td>
<td>q</td>
<td>www.automationtricks.blogspot.com</td>
</tr>
<tr>
<td>click</td>
<td>css=span.ds > span.lsbb > input.lsb</td>
<td></td>
</tr>