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.
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:
1 |
//*[@id="mc-embedded-subscribe"] |
Now that we have our Xpath, we can put it into a Watir-Webdriver command, which will look like this:
1 |
browser.element(:xpath,"//*[@id='mc-embedded-subscribe']").exists? |
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:
1 2 3 4 5 6 7 |
#XpathTest.rb require 'watir-webdriver' require 'rubygems' browser = Watir::Browser.new :chrome browser.goto "https://3qilabs.com/about/" browser.element(:xpath,"//*[@id='mc-embedded-subscribe']").exists? puts "Submit Button Exists: #{browser.element(:xpath,"//*[@id='mc-embedded-subscribe']").exists?}" |
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.