Sunday, November 23, 2014

Contains() and starts-with() function in Xpath

Certain sites like Google and Yahoo have dynamic attributes,

Eg : <input id="text-12345" />
next time when you try to run in a new sesion the same tag will have the values <input id="text-12567" />
Here 12567 is dynammically generated everytime a new session is created

To handle such dynamic attributes we can use certain Xpath functions like 'starts-with' and 'contains'

tag => <input id="text-12345" />
xpath => //input[starts-with(@id, 'text-')]

When you use starts-with, a part of xpath should remain same and other part will be dynamically generated.

What if the complete xpath is dynamically generated? In this case you cannot automate for external website, whereas if your company owns the site then you can talk to developer and get the script which dynamically generates the xpath and use in your program

contains Xpath functions

Consider the tag
tag => <span class="top heading bold">
Xpath => //span[contains(@class, 'heading')]

Contains is used when an element can be located by a value that could be surrounded by other text, the contains function can be used.

Better way of writing the same would be with CSS selectors
xpath => //div[contains(@class, 'article-heading')]
CSS => css=div.article-heading

For complex xpaths or compound xpaths

Compound Xpaths => //ul[@class='featureList' and contains(li, 'Type')]

No comments:

Post a Comment