Time for action - finding elements by XPath - Selenium

Unfortunately,best practices cannot always be followed when building the markup or if they are,then they may have a dynamic edge to them. An example of this would be working against a page that uses a key from the database as the element ID, so when something is edited and stored back in the database it can be found a lot quicker and updated.In this section of the chapter, we are going to work with XPath. XPath allows us to query the DOM as though it were an XML document.With XPath we can do some rather complex queries to find elements on the page that may not have been accessible otherwise.

Let's start by creating a basic XPath. We are going to look for an input button:

  1. Open Selenium IDE.

  2. Navigate to https://www.wisdomjobs.com/

  3. Type click into the Command selectbox.

  4. Type xpath=//input into the Target textbox.

  5. Click on the Find button.It will find a button on the page like in the following screenshot.Note that sometimes Selenium IDE will flash the button yellow:

What just happened?

Your test will have looked against the DOM to find an element that was of the type input. The xpath= at the beginning tells Selenium that the element needed will be located by XPath. It removes the guess work that Selenium would have to do and is seen as good practice. The // tells the query that it needs to stop at the first element that it finds.It is a greedy query so if you have a rather large web page, it can take some time to return since it will try to parse the page.Writing the XPathlike this allows us to make changes to the UI, within reason, and not have it impact the test.

Using direct XPath in your test

As I mentioned in the first part of this section, having // as the start of your XPath is seen as a greedy query since it will parse the entire DOM until it finds the element that you want to find.If you want to work against an element that will always be in a certain place, you can use a more direct XPath.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Selenium Topics