0

I am using Fire bug in firefox browser to identify a unique id in the web pages using the Xpath feature. Sometimes the Xpaths are not unique, ie: the xpath id is dynamic and keeps changing as the result my script fails. Can anyone let me know how to customize the Xpath so that I can still use it to uniquely identify an object?

  • Updated title to be more general. The problem is not xpath. Both xpath and css can both use ID, Class, Name, etc. just with different formats. The problem is the changing ID. You cannot use a database based dynamic ID. So you need to learn the other methods to select based on the class or css ID or the structure of the surrounding markup. Conversely, don't over-specify though or you will have a brittle layout based selector. – Michael Durrant Mar 10 '16 at 22:50
  • And see sqa.stackexchange.com/q/9669/8992 – Michael Durrant Mar 10 '16 at 22:55
1

As you just found out, Xpath is ill suited for locating elements.

Best practices recommend to use IDs or names. If you cannot, CSS selectors, or get list of elements by tag id and then filter the returned list by other criteria.

I try to avoid the Xpath like a plague. It only (and barely) makes sense if it is static, which in your case is not true. Also, Xpath is slowest way to locate elements.

0

CSS selectors wont work? Also, please put snipplet of the code you're trying to manipulate or elements you're trying to access.

0

For more stability of the scripts I can recommend to use following hacks to your XPath identifiers:

Use unique id's or names, try to make agreement with developers NOT to change id overtime:

//table[@id="example"]
//input[@name="example"]

Use another parameter which is unique:

//div[@myid="example"]

Use classname:

//div[class="classname"]

Use XPath contains function. Especially contains() can make scripts stable as developers often change prefix and suffix of the html parameter, but the core remains the same:

//div[contains(@class,"part-of-the-classname")]
//div[contains(@ng-model,"corename")]

Use XPath logic functions (and, or, not)

//div[@class="classname" and contains(@model,"corename")]

Use identification according to the text content of the tag:

//div[@class="contentclassname" and contains(text(),"ContentText")]

Use XPath "OR" if there is possibility that more than one type of the object fulfill the need:

//table[@id="resultTable"] | //div[@class="noResultWarning"]

Use XPath axes (http://www.w3schools.com/xsl/xpath_axes.asp) as descendant, following-sibling, preceding-sibling, parent. Make use of fixed elements and take the path from that element with help of axes:

//table[@id="resultTable"]/descendant::tr[@class="table-row"][1]
//table[@id="resultTable"]/descendant::tr[@class="table-row"][2]

Happy XPathing!

Not the answer you're looking for? Browse other questions tagged or ask your own question.