How to use the xpath class contains in finding elements?

319    Asked by Amitraj in QA Testing , Asked on Apr 26, 2022

Can anyone please help me how to use contains in my xpath? My xpath changes all the time when users are added, so I can't find elements using xpath. This is my xpath:

.//*[@id='contentText']/table/tbody/tr[2]/td/table/tbody/tr/td[1]/table/tbody/tr[9]/td/table/tbody/tr/td[1]/strong[2]
Changes when new user added:
.//*[@id='contentText']/table/tbody/tr[2]/td/table/tbody/tr/td[1]/table/tbody/tr[10]/td/table/tbody/tr/td[1]/strong[2]
Answered by Amit Sinha

I have tested an ExtJS application. Most of the page element attributes are dynamic. They change not only when you add a new user or something, they change every time when you open the application. I have found the xpath class contains expressions I get from the tools (Firebug etc.) are not very useful. Here is why:

hard to read
break easily
hard to debug

What I do instead, is rather to spend time looking at the HTML and identify possible unique attributes that are not dynamic and come up with my own expressions. If none of the attributes are static for a certain element, use any other element on the page that does have static attributes with the parent/child/sibling relations to locate.

I often use "contains", but there are more. Here are some examples:
multiple condition: //div[@class='bubble-title' and contains(text(), 'Cover')]
partial match: //span[contains(text(), 'Assign Rate')]
starts-with: //input[starts-with(@id,'reportcombo')]
value has spaces: //div[./div/div[normalise-space(.)='More Actions...']]
sibling: //td[.='LoadType']/following-sibling::td[1]/select"
more complex: //td[contains(normalise-space(@class), 'actual cell cell-row-lines saj-special x-grid-row-collapse')]


Your Answer

Interviews

Parent Categories