Testing Finding a Non-Unique Button with XPath
In this study, a stable way of selecting elements is demonstrated by using the powerful features of XPath.
One of the challenges we face when doing web test automation is identifying the unique element.
The web page we will review has a non-unique "Ucretsiz ?ptal" button.
When I want to select the relevant element, I can see that there is more than one in the dom;
//a[contains(.,'ücretsiz ?ptal')]
My target item here is to click on the "Free Cancellation" button in front of the "Citroen" brand vehicle. You may think that we can do this using index, but if you are a good automation tester, you know that new cars may be added to the page and the index may drift and your code will become vulnerable to changes. Therefore, to make the unique selection, we will try to find the relevant element in the parent in the xpath's dom tree.
//strong[text()='Citroen C Elysee']
Now to proceed to the ancestor of this item;
//strong[text()='Citroen C Elysee']/..
/.. this way we will find the parent of the xpath element
Now that we are in the parent element, I will look for the target button here, so I will go to the parent as /.. and look for the button as //a[contains(.,'ücretsiz ?ptal')].
//strong[text()='Citroen C Elysee']/..//a[contains(.,'ücretsiz ?ptal')]
However, I cannot find an item in a parent parent, so I try a parent parent;
//strong[text()='Citroen C Elysee']/../..//a[contains(.,'ücretsiz ?ptal')]
I was able to access the button located in the child element of the two parent parents.
Now my automation will be able to work more stable regardless of the order.