top of page
Livya Dhilip

How to effectively use Selenium locators

Introduction:


Selenium is the most powerful framework when it comes to Web Automation Testing and Selenium Locators are considered constituent for test scripting. The locators in Selenium plays a significant part in identifying GUI elements to perform required operations.


What are Locators in Selenium?


Locators helps users to interact with Web elements to achieve certain operations (i.e click, enter text, get text).

We have different types of locators in Selenium Webdriver which helps users to interact with Web elements and choosing appropriate locators is essential to avoid failure in your tests. The following are the list of locators in Selenium


· ID

· Name

· Class Name

· Linktext

· Partial Linktext

· XPath

· CSS Selector

· Tag Name






LOCATORS

DESCRIPTION

SYNTAX

ID

Identify the WebElement using the ID attribute

driver.findElement(By.id(“IdValue”));

Name

Identify the WebElement using the Name attribute

driver.findElement(By.name(“nameValue”));

ClassName

Identify the WebElement using the ClassNameattribute

driver.findElement(By.className(“classValue”));

LinkText

Use the text in hyperlinks to locate the WebElement

driver.findElement(By.linkText(“textofLink”));

Partial LinkText

Use a part of the text in hyperlinks to locate the desired WebElement

driver.findElement(By.partialLinkText(“PartialTextofLink”));

TagName

Use the TagName to locate the desired WebElement

driver.findElement(By.tagName(“htmlTag”));

CssSelector

Use CSS to locate the WebElement

driver.findElement(By.cssSelector(“cssValue”));

XPath

Use XPath to locate the WebElement

driver.findElement(By.xpath(“xpathValue”));

How to Identify WebElements?


1. Open a web application, right click ‘Inspect’ or Press F12 to open the browser DOM (Document Object Model).



2. The Developer tools opens up and by default ‘Element’ section is selected.



3. Click on the mouse icon and hover over any of the web element you would like to locate. DOM would be highlighted when you click on the element as shown below.



4. We can use the locators (id, tagname, classname) to locate the objects which we will be seeing in this blog.


Locating a Web Element by an ID:


The most effective way to find a Web Element in a web page is by an ID. ID’s are expected to be unique for each element in DOM and due to which it is considered as a fastest and easiest method to locate elements, however incases where the IDs are not unique, we may use other techniques to locate objects in Selenium WebDriver.


By choosing the ID locator above other locators would be efficient and this would expedite the Selenium test cases execution.

Below is an example on how to locate a Web element using ID.


<input type="text" id="firstname" name="firstname" value="" title="First Name" class="input-text required-entry" data-validate="{required:true}" autocomplete="off" aria-required="true">

driver.findElement(By.id("firstname"))

If there is no element found for the ID then NoSuchElementException error is displayed thus it is significant to have an idea on exceptions and knowledge on locators to build a vigorous Selenium framework.


Locating a Web Element by Name:


Another way of finding an element is by its ‘Name’. ID locators are unique in a web page whereas Name locator may or may not have a unique value. If there are more than one with the same name, the locator picks the first element with that Name on the webpage.


We can use the same example for ‘Name’ which used to locate ID.



<input type="text" id="firstname" name="firstname" value="" title="First Name" class="input-text required-entry" data-validate="{required:true}" autocomplete="off" aria-required="true">

driver.findElement(By.name("firstname"))

Locating a Web Element by ClassName:


Class Name locators are used to locate elements those are defined using class attribute. Below is an example on how to locate using Classname and its syntax.


<input type="checkbox" name="is_subscribed" title="Sign Up for Newsletter" value="1" id="is_subscribed" class="checkbox" xpath="1">

driver.findElement(By.className("checkbox"))

Locating a Web Element by Linktext:


Elements can be located via link text that is present in the hyperlinks. The link should be unique otherwise the locator will pick the first matching element.


In the below example, we have to give the link name ‘Sign In’



<a href="https://magento.softwaretestingboard.com/customer/account/login/referer/aHR0cHM6Ly9tYWdlbnRvLnNvZnR3YXJldGVzdGluZ2JvYXJkLmNvbS9jdXN0b21lci9hY2NvdW50L2NyZWF0ZS8%2C/" xpath="1">Sign In </a>

driver.findElement(By.linkText("Sign In"))

Locating a Web Element by PartialText:


We use partial link text when the link name is too long. This is handy in most of the cases as we need not type in full link name.



<a href="https://magento.softwaretestingboard.com/customer/account/create/" xpath="1">Create an Account</a>

In the above example, ‘Create an Account’ is the name of the link however we need not give the fullname. In PartailText locator it will work if we give something like below.



driver.findElement(By.partialLinkText("Create"))

Locating a Web Element by TagName:


As the name specifies, the Tag Name locator in Selenium uses tag names to identify elements on web pages. The tag name is basically the HTML tag such as input, div, button, anchor, span etc.


TagName can be used with Group elements, i.e- Select and check-boxes/dropdowns.



In the above example, ‘Select’ is the TagName of the dropdown and the desired dropdown value to select is ‘Iphone’. First, we have to reach the Tagname ‘Select’ and then choose the value within the dropdown. Below is the syntax to locate it.



Select select = new Select(driver1.findElement(By.tagName("select")));

select.selectByValue("Apple");

Locating a Web Element by Xpath:


XPath is the most widely used locator that helps in locating elements on the webpage using XML expressions.

The syntax of XPath is : //Tagname[@Attibutename = ‘value’]


The above syntax represents four components:


  • Double forward slash(//) – Denotes the current node

  • Tagname – Denotes the tagname in DOM structure, tagname can be input, tag, anchor tag etc

  • Attributename – Denotes attribute of a particular tag. Attributes are prefixed with ‘@’ and their value like @input, @tag.

  • Value – Denotes the value of a defined attribute

Types of XPath:


  • Standard XPath

  • Using Contains

  • Using XPath with AND & OR

  • Using starts-with

  • Using text in XPath


Standard Xpath:


As the name implies, this is the Standard way of writing Xpath in Selenium. Let’s look at an example to understand the structure of writing Xpath.


  • //- Current node

  • Input- Tagname

  • @id- @ should be used before the Attribute name.

  • Firstname- It is the value of an attribute ‘id’


Here is how we locate with ‘Standard Xpath’


driver.findElement(By.xpath("//input[@id='firstname']"))

Xpath using Contains tag:


Xpath contains can be used when there is a dynamic Webelements on the page, which means the webelement value would be changing frequently.

"contains()" is used when we are familiar with some part of the attributes value of an element.


Syntax:


//tagname[contains(@attribute, ‘partial value of attribute’)]



Here is how we locate with ‘Xpath Contains’



driver.findElement(By.xpath("//input[contains(@name, 'last')]"))

Xpath using AND & OR:


The ‘AND’ & ‘OR’ operators are used in finding a webelement based on condition. In the case of ‘OR’ either of the condition should be True. In the case of ‘AND’ both the condition must be True.


Syntax:


//tagname[@attribute=’value’ or @attribute=’value’] - //input[@id='email_address' or @name='email']


//tagname[@attribute=’value’ and @attribute=’value’]- //input[@id='password-confirmation' and @name='password_confirmation']


Let’s see an example below with both the operators.





driver.findElement(By.xpath("//input[@id='email_address' or @name='email']"))


driver.findElement(By.xpath("//input[@id='password-confirmation' and @name='password_confirmation']"))

Xpath Text():


Xpath Text is used to locate elements based on text of a web element. It helps to find the exact text elements and it locates the elements within the set of text nodes. The elements to be located should be in string form.


Syntax:



//tagname[text()=’value’]- //span[text()='Create an Account']

Let’s see an example how it works.




driver.findElement(By.xpath("//span[text()='Create an Account']"))

Xpath Starts-with():


Xpath starts-with() is a method that finds those elements whose attribute value changes on refresh on the web page. This method checks the starting text of an attribute and finds elements whose attribute changes dynamically.


Syntax:



//tagname[starts-with(@attribute, ‘attribute name starts with’) - //input[starts-with(@id, 'email')]

Let’s see an example how it works.




driver.findElement(By.xpath("//input[starts-with(@id, 'email')]"))

Locating a Web Element by CssSelector:


CSS Selectors in Selenium are string patterns used to identify an element based on a combination of HTML tag, id, class, and attributes. As such they are patterns that match against elements in a tree and are one of several technologies that can be used to select nodes in an XML document. CSS is said to be more reliable than XPath and is faster than XPath.


Types of Css:


  • Tag and ID

  • Tag and Class

  • Tag and Attribute

  • Tag, Attribute and Class

  • Wildcards in CSS

Tag and ID



syntax:


<tagname#id of an attribute>


  • HTML tagname- i.e input tag

  • #- It represents ID attribute. The # should be used only for ID and don’t have to use for other attributes.

  • Value- This implies the value of the ID attribute


Let’s see an example how it works.




driver.findElement(By.cssSelector("input#firstname"))

Tag and Class


It does the same purpose as above but just the syntax changes.


Syntax:


tagname.Class value attribute


Tag and Attribute


Tagname[Attribute=value]





driver.findElement(By.cssSelector("input[name='password']"))

CSS- Wildcard-Start of String


Tagname[Attribute^=Start of the String]




driver.findElement(By.cssSelector("input[name^='pass']"))

CSS- Wildcard-End of String


Tagname[Attribute$=End of the String]




driver.findElement(By.cssSelector("input[name$='word']"))

CSS- Wildcard-Contains()


Tagname[Attribute*=partial String]




driver.findElement(By.cssSelector("input[class*='mage']"))

Best Practices on using Selenium Locators:


  • Avoid using dynamic elements

  • Locator preference based on hierarchy to speed up the execution

  • Always use a unique ID for element identification

  • Consider using short locators

  • Don’t be dependent on tools for Xpath and CSS

Conclusion:


We have come to end of this blog. To summarize, we have gone through various ways of locating webelements using Selenium locators. We have also seen how to easily locate elements using id,name,classname,tagname,linktext,partialtext, Xpath and CSS.


Selenium locators helps to build a robust Automation framework. I hope this blog helped you to learn about Selenium locators and you should be able to work independently.


1,262 views
bottom of page