Limited Period Offer - Upto 50% OFF | OFFER ENDING IN: 0 D 0 H 0 M 0 S

Log In to start Learning

Login via

  • Home
  • Blog
  • Explain about the Locators ...
Post By Admin Last Updated At 2020-09-16
Explain about the Locators in Selenium and its usage

Locating web elements and automating them is a complex task. If you’re one of those who are looking for the easiest way to locate elements on the web, then this blog post will guide you. Here, we will discuss on the locators in Selenium and their usage. Moreover, we also look into the different types of locators in Selenium. At first, we will go with the Locators in Selenium; definition. **What is Locators in Selenium?** Locators provide a way to recognize an HTML element upon a web page. Moreover, all UI automation tools also provide the ability to use locators to identify HTML elements on a web page. Similarly, Selenium also uses “*Locators*” for identifying HTML elements. The locators in Selenium infrastructure are powerful commands that are useful to execute actions on the text boxes, links, checkboxes, and other web elements. These are the fundamental building blocks for a web page. And a web developer must use a proper and consistent locator for a website for better visibility. Locating the exact GUI element on a web page is a prerequisite for creating the best automation script. But finding an exact and accurate GUI element is not an easy task for anyone. It is the place where locators come into the scenario. Moreover, choosing the right locator gives the benefit of faster testing and more reliability over further releases and its management. Further, in this regard, we will look after the different types of locators in Selenium.

**How to use multiple locators in Selenium**

A good script or coding with a strong base needs all elements to be located in proper places. There are multiple types of web elements such as text box, id, radio button, etc. Moreover, it needs an effective and exact approach to recognize these elements. Hence, we have multiple locators in Selenium to use for identifying correct HTML elements. The below stated are the multiple types of “Selenium locators”.

  • ID
  • Name
  • TagName
  • CSS Selector
  • Linktext
  • Partial Linktext
  • Xpath
  • Class Name

The above are the various locators in Selenium and we will discuss each of them with examples. Get more practical knowledge on locators in Selenium with Selenium Online Course.

**ID Locators in Selenium**

The most popular and common way of locating web elements as a whole. These are unique to each element within the DOM or Document Object Model. Also, the ids are considered as the safest and fastest method to locate elements. And these should always be the first option among the multiple choices available. For example – we can check the employee Number or Account which will be a unique id. Generally, the ID should not repeat on a web page, but the browser allows exceptions to this rule. There is no doubt that “ID” is the best locator to use within Selenium. But, in case it belongs to an HTML table, then it’s possible that it would change or transform from the list. Hence, users need to put in a more advanced locator technique in this regard for use. The following snippet will help us to understand the ID syntax to use. \WebElement item = driver.findElement(By.id("user"));

**Name Locators in Selenium**

There are multiple attributes useful to find an element on a web page. The “Name” attribute is one of them. The ‘Name’ locators in Selenium WebDriver are also useful to locate elements such as ID locators. They may or may not be unique on a web page with different elements. In case there are several elements with the same name, then the locator chooses the first element with that name on the page. By using this strategy, the first element having the value of the “name attribute” will be returned. In case, there no element that has the same name attribute, then a “No Element” will be raised. Hence, it is always recommended that make sure the value of the “name attribute” should be uniform. This has to be unique while selecting it for locating a web element. The following code helps us to understand the Name locators in Selenium. \WebElement locator = driver.findElement(By.name("admin"));

**Link Text Locators in Selenium**

The *link text*helps users to identify the hyperlinks on a web page. It is controlled with the help of an anchor tag (Example: \). To build the hyperlinks upon a web page, the users can use anchor tags with link Text to find links. Below is an example code for link text. WebElement item = driver.findElement(By.linkText("How to use locators?"));

**Partial link Text Locators in Selenium**

Locating an element using *Partial Link Text* is similar to the normal Link Text locator in Selenium. The reason for using the Partial Link Text locator in Selenium is only to avoid the long *link text*. While having long text and the user intends to use only partial text to execute further actions, then he can use *partial link text*. The following example text is useful to understand partial link text. How to use locators?\WebElement item = driver.findElement(By.PartialLinkText("How to use locators?"));

**Tag Name Locators in Selenium**

The Tag Name is a kind of CSS locators in Selenium. This is useful to identify web elements using Tag Names like div tag, a tag, etc. For example; we can use the *Tag Name* attribute in this way. We can make identifying links on the homepage and verifying them that they are functional or broken. \|\|\{"title":"Master in Selenium"\, "subTitle":"Selenium Certification Training by ITGURU's"\, "btnTitle":"View Details"\,"url":"https://onlineitguru\.com/selenium\-training\.html"\,"boxType":"demo"\,"videoId":"SsWf3LjoT5Y"\}\|\| Moreover, the Tag Name locator is useful to locate the elements matching the specific Tag Name. It is very much useful while we extract the content within a Tag. List\ linkElements = driver.findElements(By.tagName("results"));String[] linkTexts = new String[linkElements.size()];**CSS Selector Locators in Selenium**

The *CSS Selectors* within Locators in Selenium are the selector patterns useful to locate a web element. This includes a combination of HTML tag, id, class, and attributes. Identifying by CSS Selector is a more complex job than the earlier methods. But it is the most common identity strategy of advanced Selenium locator users. This is much popular as it can access even those elements that don’t have an ID or name. CSS (Cascading StyleSheets) Selectors include many types, but we will only focus on the most common selectors in use.

  • a)     Tag and ID
  • b)     Tag and class
  • c)     The Tag and attribute
  • d)     Tag, class, and attribute
  • e)     Inner text
  • f)      Child Elements
When using this plan, we always prefix the destiny box with "css=". The following example will explain this thing; WebElement CheckElements = driver.findElements(By.cssSelector("input[id=email']"));

**Using Tag and ID**

This is represented by using the “css=tag#id” syntax. The description for the above syntax includes;

  • tag = this is the HTML tag of the web element for accessing
  • \# = the hash sign should always exist while using a CSS Selector with ID\.
  • id = the ID of the web element for accessing

**Using Tag and Class**

Identifying by CSS Selector with an HTML tag and a class name is similar to using a tag and ID. But in this case, a dot (.) is used in the place of a # sign. With the help of the following example, we will try to understand Tag and Class. The syntax for the tag & class is; "css=tag.class" The below is the description for this CSS selector.

  • tag = this is useful for accessing the “HTML tag” of the element
  • . = while using a Selector with class, the (.) sign should always exist there
  • class = the class of the element is accessible

**Using Tag and Attribute**

This is useful to access the HTML tag & attribute of the web element. The syntax follows; css=tag[attribute=value]The description of this attribute and tag is;

  • tag = useful to access the HTML tag of the element
  • [ and ] = the square brackets within represent a specific attribute and its corresponding value to be arranged
  • attribute = the usage of an attribute is advised here that is unique to the element like a name or an ID.
  • value = this denotes the respective value of the chosen attribute.
The Tag, class, and attribute is also similar to the above Tag and Attribute element usage. The syntax of this is; css=tag.class[attribute=value]

**Using Inner Text**

The “**inner texts**” are the real string patterns that the HTML label visualizes on the web page. The syntax and description for the “*inner text”* is as follows; css=tag:contains("inner text")·        tag = denotes accessing of HTML tag ·        inner text = denotes the “inner text” of the web element.

**XPath locators in Selenium**

XPath or XML path is the language useful to query XML docs while identifying XML (Extensible Markup Language) nodes. Since HTML can be utilized as an XML file, we can also use XPath in identifying HTML elements. Moreover, this is a perfect technique to go through the DOM structure of the web page. XPath locators within Selenium locators are robust and reliable. It is one of the methods that guarantee to identify any element on the page with the XPath expressions. The general syntax useful for using XPath as a CSS locator within locators in Selenium is: Xpath: //tagname[@attribute='value']In the above syntax, the “tagname” mentions the tag within the DOM structure that we are linking to. The multiple attributes such as name, id, class, etc., are also useful in this regard. Moreover, there are different ways using which XPath can be defined in various ways. There are two different types of XPath available; absolute and Relative XPath.

**Absolute XPath**

The absolute XPath begins from the root element in the web page and reaches to locate the target element. This Xpath expression helps to locate the UI elements much faster. They usually include the Complete or Full path of the UI element from the root/beginning. The basic syntax for absolute XPath is; HTML/head/body/table/tr/tdMoreover, this is the direct path to locate any element. But the XPath will break or fail when the element structure modifies.

**Relative XPath**

The Relative XPath is easy to manage as it is very short and concise and start from the middle of the HTML DOM structure. This path is also better than the earlier XPath style. It may survive the modifications within the HTML page to a definite stage. Hence, creating a relative XPath is much time-consuming. Moreover, it’s quite tricky also as the user needs to check all the nodes to form the path. Relative XPath syntax example is: //table/tr/td\|\|\{"title":"Master in Selenium"\, "subTitle":"Selenium Certification Training by ITGURU's"\, "btnTitle":"View Details"\,"url":"https://onlineitguru\.com/selenium\-training\.html"\,"boxType":"reg"\}\|\|

**Selenium locators best practices**

For efficiently using the Selenium locators, we must follow some best practices and rules laid for it.

**Don’t use active attribute values to locate HTML elements:**

As per laid down rules, it is suggestible not to use highly active attribute values to identify elements. Because they may frequently alter and result in failure or break-down of a locator script. Besides, it also greatly affects the management, reliability, and productivity of the automation scripts. This is one of the basic rules that one needs to keep in mind while writing a better automation script using locators. In case a locator is dependent on a single entity like for example class, name, id, etc., need to be repaired if changes. Try to make your locators in this section accurate and dependent on a single entity than several. The “ID and name” attributes take priority over other locators. In case the user’s web page includes a unique ID & name, then it’s always suggestible to use them. They are alternative to XPath as they are much faster and more productive. Typically IDs are auto products and while identifying them and using them in codes could be difficult. Hence, every time the code or page including ID’s is run they move to change and make user scripts break. While using locators, the user has to make sure that his locator points exactly to the required element. If the required plot needs to execute some process on a single element, then he should make sure that the locator truly matches to only one element. Furthermore, in case the locator points to some multiple elements, then it may put a break in the script.

**Never use locators to identify auto-produced elements on the web page**

Sometimes in an active web ecosystem, element attribute properties are produced at run time. One should eliminate these elements as they may put a break while scripting performance.

**While selecting locators in Selenium, don’t use XPath or CSS Selector supplied by the Dev Tools**

While doing work with XPath or CSS locators, one should eliminate the direct usage of them produced by the “Chrome Dev Tools”. Moreover, this seems to be the easiest way to produce XPath, but in the long run, it induces reliability issues, script breakage, managing errors, etc. It may look alluring to use these scripts. But the user should build his custom XPath in the long run and for better usage and results.

**Summing Up**

Using the locators in Selenium helps in locating the web elements easily and also useful in automating them. With the help of locators, it becomes easier to identify the HTML elements on the web page. Moreover, the usage of accurate locators makes helps the developer to provide great visibility to the web page. Thus, these are the base for a web page. To learn more about the locators in a practical way from an expert’s voice, take deep dive into Selenium Online Training.