TestComplete Tip: Getting XPath Expressions for Web Objects Faster

  September 02, 2013

Web pages contain tons of elements, and finding the correct element for a specific test case can be quite the ordeal. TestComplete includes the EvaluateXPath and FindChildByXPath methods that help you quickly find Web objects with XPath expressions that include the objects' names, positions and attributes. XPath, otherwise known as XML Path language, is a query language used for navigating through elements and attributes in XML documents. It is also used for HTML elements. This post will help you quickly incorporate XPath expressions into our test scripts. I hope it will be useful for both those not familiar with XML and for those want to get XPath expressions faster.

In fact, getting the XPath expression for a Web object is a simple copy and paste action. You can do this in special developer toolbars and windows available in popular browsers like Google Chrome or Mozilla Firefox. Let see how you can get it with Google Chrome:

  1. Open your tested web page in Chrome.
  2. Once the page is loaded, press F12 to open the Developer Tools window (it will appear at the bottom of the browser window).
  3. Switch to the Elements tab:

elements-xpath-expression-testcomplete

      4.Click the magnifying glass button at the footer and then click the test element on the page for which you would like to get the XPath expression:

 

search-xpath-expression-testcomplete

(Note that when you click the desired element, it will be automatically selected in the hierarchy of elements in the Developer Tools window.)

      5.Right click the desired element in the hierarchy and choose Copy XPath from the context menu. This will copy the XPath expression for the element to the clipboard:

copy-xpath-expression-testcomplete

 

Now you have the XPath query that is needed for your test script. Paste it in your test code where it is necessary.

If needed, you can modify the copied expression. For example, you can include specific attribute values to make recognition settings independent on the page object structure, for example:

  • Copied XPath:

//*[@id="gc-content"]/div[1]/div/p[2]

(selects the p object by its position in the parent object).

  • Modified XPath:

//*[@id="gc-content"]/div[1]/div/p[@class="note"]

(selects the p object, whose class attribute is equal to note).

Hope this tip will make creating tests for your web applications much easier. We are always waiting to hear your feedback, so feel free to drop a line below or visit the SmartBear product forums to share your opinion with the community.

See also: