CosmoCode (Formerly TeachMeSelenium)

Identifying elements in the page | Inspect attributes like id, class, name etc of an element

  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.

<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 – class, id, 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.

What do you mean by uniquely identifying the 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 email. If we use this attribute/value pair with Selenium, it will act on the first matching element on the web page while ignoring the rest of the matching elements. And it may be the case that we actually wanted the second element.

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 Ctrl+f or Cmd+f to open the search window. You can search for the attribute value and check if it appears in the search result.

That is impressive. It means we can locate all elements on the page so easily.

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.

Exit mobile version