Thursday, September 18, 2014

Finding relative x-path of dynamic headings/text on pages whose attribute is unavailable.

For instance, We are on web page which has dynamic heading(its being changing everytime whenever we refresh the same page) like this 
In first visit page heading was 
"My first example 1",
after refresh its now 
"My first example 2" 
and then 
"My first example 3" 
and
"My first example 4" and so on....
when we check this in web debugger their HTML is as follows:-

<span>My first example 1</span>
<span>My first example 2</span>
<span>My first example 3</span>
<span>My first example 4</span>.... here we have starting tag box and ending tag box without any attribute.

From above span we can say that we don't have any attribute with this, If it has class attribute then it will appear as 
<span class= "example">My first example 1</span>, 
then we could have used that attribute to create xpath //span[@class='example']
but here scenario is different,So to pick that heading we will use 'contains' and 'starts-with function' to make relative x-path as follows:-
//span[contains(text(),'My first example ')]
Or we can use 
//span[starts-with(text(),'My first example')]
Webdriver will look into our HTML it will search for 'span'(tagname) which contains any text with 'My first example' regardless of its being changed to 'My first example 2', 3 , 4 and so on...
Note:- This will work for those elements which has both starting and ending tags like in above example <span>......</span>

No comments:

Post a Comment