Working with XPaths

Prev Next

Recording In certain cases, using the Catchpoint recorder may not produce the expected results. For example, consider a script to open Amazon.com, search for boots, and open the first result. The recorded script would look like this, and may fail:

// Step - 1
open("https://www.amazon.in/")
setStepName("1. Homepage")
click("//*[@id='twotabsearchtextbox']")
type("//*[@id='twotabsearchtextbox']", "boots")

// Step - 2
clickAndWait("//*[@id='nav-search-submit-button']")     setStepName("2. Search Page")

// Step - 3
clickAndWait("//span[@class='lrg.bold']")
setStepName("3. Detail")

In the image below, the transaction fails on step three, but it is not clear as to why:

missing.png

amazon.png

The screenshot was enabled before running the test, and indicates the script is failing to click on the first result. Using developer tools in the browser (in this example, Chrome), manually perform the Transaction until you arrive at the step with the error. After right-clicking and inspecting the element causing the failure, copy the XPath:

With the XPath for the element, compare it to the XPath used in the original script. Notice the two are different and may be why the transaction was failing.

  • Original Action: clickAndWait(//span[@class='lrg.bold'])
  • New Action: clickAndWait("//*[@class='s-image']")

Modify the script, run the transaction, and it works as intended!

amazon_pass.png

Troubleshooting The example illustrated above is a simple problem that was easy to get around, but sometimes transactions are a little bit more tricky. Developers often give multiple elements the same id names, which can throw Selenium off because the page may contain two instances of that id. A workaround for this is to use both the id and class when specifying the location. Another option is to set the locator as the XPath of the div containing the element that the script is intended to click.

XPath
XPath is a language used for parsing XML documents. It takes advantage of the tree-like hierarchical structure of the XML DOM. An example XML document:

<store>
    <item type="food">
        <name>bread</name>
    </item>
    <item type="drink">
        <name>milk</name>
    </item>
</store>

To select the item with the name "bread", you can use XPath as follows:

/store/item[@type="food"]/name/text()

Catchpoint supports the following XPath locators:

//img[@alt='The image alt text']
//table[@id='table1']//tr[4]/td[2]
//a[contains(@href,'#id1')]
//a[contains(@href,'#id1')]/@class
//table[@class='stylee'])//th[text()='theHeaderText']/../td
//input[@name='name2' and @value='yes']
//*[text()="right"]

For additional information, see More information on Working with XPaths.