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?
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.
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:
Use another parameter which is unique:
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:
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: