The Issue

When attempting to use HTML identifiers (such as IDs and Class) to specify a browser element while constructing automation scripts, you may encounter an element that is just not accessible, despite trying a multitude of Watir Webdriver command variations. While you can attempt to use index (as discussed in a previous How To post), there is another option available: Xpath.

The Answer

The Xpath of an element is essentially a direct, precise roadmap to the specific element you are trying to select for your automated test. Here’s a walkthrough of how to obtain the Xpath of an element, using the 3Qi Labs website ‘About’ section. We can obtain our Xpath by inspecting the element we want.

This element in our DOM will have a unique Xpath that allows us to specify it for browser testing.

The highlighted element we will be taking the Xpath from.

Then, we right click on the highlighted element in the inspector, and select Copy>Copy Xpath.

The Code

After copying an Xpath, we will receive a line of code we can eventually utilize in our test automation. Here is the code we received from our Xpath in the previous section:

Now that we have our Xpath, we can put it into a Watir-Webdriver command, which will look like this:

Now that we know how to obtain Xpath and put it into a Watir Webdriver Command, lets create a sample automation script utilizing Xpath. This script will navigate to the 3Qi Labs ‘About’ section, and click the submit button:

The Result

We can save the file (XpathTest.rb) and run it from the command line, with the following result:

  • Browser opens
  • Browser navigates to the 3Qi Labs ‘About’ URL
  • Validates if the Submit button exists

The Takeaway

As long as the browser element exists, you can obtain the Xpath for interactions with Ruby, Selenium, and Watir Webdriver. Using Xpath will allow to have a direct way to pinpoint your desired element and utilize it in a Watir-Webdriver command. This will your automation script writing process become more efficient by eliminating time wasted searching for a working element identifier.