In the Previous Tutorial, we wrote and run our very first Selenium script. In this tutorial, we will explore different ways of identifying elements in a web page. We’ll try to uniquely identify elements in the page using its one of the following attributes –
What is a UI element in a web page?
A webpage consists of different UI items – buttons, links, inputs boxes, drop-down lists, checkboxes, radio buttons, plain texts etc. These are called WebElements or Objects in Test Automation world.
In order to perform any action (like click, type, select etc) on these elements, Selenium needs to locate them uniquely on the page. To help Selenium locate these UI elements, we need to find their properties on the page.
In this website, we’ll use Google Chrome’s developer tool to inspect properties of UI elements. The developer tools is in-build with the Chrome browser. You are free to use other tools like Firepath for Mozilla Firefox or IE’s developer tools.
Inspecting a UI element
Let us take an example of the Google homepage. In this page, we will try to find the attributes of the ‘Google Search Box’ element.
- Let us launch the Google Chrome browser and navigate to www.google.com.
- Right-Click on the ‘Google Search Box’ and select ”Inspect Element’
- The above operation should display the HTML source code snippet for that element (Google Search Box)
- The HTML source code snippet displayed in the above screenshot contains the attributes or properties for the ‘Google Search Box’ element.
- Let us look closely at it. I have omitted most of the attributes so that we can focus on the required attributes.
<input class="gsfi" id="lst-ib" name="q"
As we can notice the ‘tag name’ for the element is
input. It has the following attributes –
name and some more. Selenium WebDriver provides means through which we can use these attributes to locate that element.
Here is a catch. We must use the attribute that can uniquely identify any element.
Well, it may happen that there are multiple elements on the page that have the same value of a particular attribute. Like, they all have
class attribute whose value is
How to search for an element on the page?
We can use the search functionality of the Chrome developer tools. Click the
Elements tab in the inspect window and use
Cmd+f to open the search window. You can search for the attribute value and check if it appears in the search result.
No, my dear. You are not that much lucky always. Sometimes none of the properties can be able to identify that element uniquely. In that case, we will use XPath and CSS selectors.
What is that?
We have covered it in the Next Tutorial.