Selenium is a widely used test automation framework. Through Selenium, you can automate any interactions such as type, click, double click with the Document Object Model (DOM) web elements.
Locators in selenium is one of the most essential components of automation testing. Locator is a unique identifier to locate specific web element on a webpage.
What is web element and how to locate web element.
Before moving into locators first let`s understand what is web-element and how to locate it.
Web element is an any element which is present inside the web page.
e.g.: link, textbox, button, radio-button, image, text, alert, drop-down, check box etc.
Let`s understand how to locate element in a Document Object Model (DOM) or in web page. If you want to locate textbox, move your mouse pointer to that text box and do right click button and select inspect option. Once you click on Inspect option one HTML page will appear it is called a Document Object Model. It is a programming interface for web documents. It represents the structure of a document as a tree of objects, where each object corresponds to a part of the document, such as elements, attributes, and text. Every web element in the DOM has a unique address that Selenium can use to locate. Therefore, it would be best to use a locator to locate a web element in the DOM.
Advantages of Locators in Selenium WebDriver:
There are multiple advantages of locators in Selenium WebDriver, some of which are listed below:
Once the web element is located on the web page, it can run the same tests on different browsers installed on various platforms. Thus, helping to perform the cross browser testing efficiently.
A web element can be located using different locator strategies in Selenium WebDriver. If the web element has an ID and name, it can be located using its ID, Name, XPath, or CSS Selector. Similarly, the respective tagName or the className can locate the same WebElement. Hence, there is a lesser chance that the tester might face difficulty locating a WebElement.
Once a WebElement is located, it can be reused in the tests, thus saving the tester effort and time while writing the test script. This also helps remove redundancy and create robust test scripts.
CSS Selectors can locate the WebElement in multiple ways, such as using ID and tagName, className, ID, other attributes, etc. Similarly, XPaths could also locate the WebElements using relative or absolute path. ID is the fastest of all locators; however, it requires that the WebElement should contain the ID attribute. The same applies to the Name locator as well.
The point here is that every locator serves different needs, so if ID and Name are not available in the WebElement, CSS Selector or XPath could be used to locate the WebElement, thus making the way out for testers so they don’t get blocked.
Different Types of Locators in Selenium WebDriver:
Following are the Different types of locators in selenium WebDriver.
ID
Name
ClassName
LinkText
Partial LinkText
TagName
CSS Selector
XPath
To work on a web element using Selenium, we need to first locate it on the web page. Selenium provides us above mentioned ways, using which we can locate element on the page. To understand and create locator we will use the following HTML snippet.
Lets see one by one locators in detail and their syntaxes.
ID locator: ID locator is one of the most preferred and fastest way to locate desired WebElements on the page. ID locators are unique for each element in the DOM.
To use ID locator, we need to call .find_element_by_id() method of the webdriver class.
2. Name Locator: Like ID locator we can locate the element by using Name locator. If there are WebElements with the same name, the locator selects the first element with that Name on the page.
In case no such name matches with the defined attribute value, NoSuchElementException is raised.
3. ClassName: ClassName locator is used for locating WebElements defined using the class attribute. The HTML page web element can have attribute class. We can see an example in the above shown HTML snippet. We can identify these elements using the class name locator available in Selenium.
WebDriver driver = new ChromeDriver(); driver.findElement(By.className("information"));
4. LinkText: Elements can be located by LinkText, which is present in the hyperlinks. For example, the first link would be selected in a scenario with multiple links of the same text.
However, this identifier strategy can only be used for elements with an anchor( < a > ) tag.
WebDriver driver = new ChromeDriver(); driver.findElement(By.linkText("Selenium Official Page"));
5. Partial LinkText : Locating WebElements using Partial LinkText is preferred when the link text is too long.The link text is the text displayed of the link. We can pass partial text as value. The partial text helps identify and use a unique element to perform further actions on it. Sometimes, this can also be locating multiple links on a page with a common partial text.
WebDriver driver = new ChromeDriver(); driver.findElement(By.partialLinkText("Official Page"));
6. TagName: As the name specifies, this CSS locator in Selenium WebDriver is used to identify elements using tag names like div, table, h1, etc.
The TagName locator in Selenium is commonly used to identify all the links on a page and identify broken links in Selenium. It is also used to get the header or the title of the web pages.
WebDriver driver = new ChromeDriver(); driver.findElement(By.tagName("a"));
7. CSS Selector: CSS (Cascading Style Sheets) is used to style web pages. At the same time, CSS is also one of the widely-used ways to locate WebElements in the DOM. The CSS Selector in Selenium should be chosen if you cannot locate an element using ID or Name locators. It can be chosen over the XPath locator. The format we follow is css =[attribute=value] .
WebDriver driver = new ChromeDriver(); driver.findElement(By.cssSelector("#fname"));
7. XPath: XPath locator in Selenium helps locate elements on the web page using XML expressions.
XPath in Selenium can be used in multiple ways.
Absolute XPath :
It's a direct path from the root element to the desired element. It starts from the root node and ends with the desired node, providing a complete path.
for example:
<html>
<body>
<div>
<p>Hello, world!</p>
</div>
</body>
</html>
To find the <p> tag using an absolute XPath, you would start at the root <html> tag and provide the full path to the <p> tag:
WebElement paragraph = driver.findElement(By.xpath("/html/body/div/p"));
Relative XPath:
It starts from any node and ends with the node you want to select. It's more flexible and preferred in most cases, as it's not affected by changes in other parts of the HTML structure. A relative XPath allows you to locate elements starting from any location within the HTML document, not just the root. The relative XPath expression usually starts with //.
XPath Contains: XPath similarly contains works like CSS Selector contains. It is extensively used on WebElements, whose value changes dynamically. Consider an example where the value of the login changes after appending the login text.
Here, XPath contains will be super-helpful in locating the desired WebElement.
Syntax:
driver.findElement(By.xpath("//input[contains(@class, 'form-control')]"))
XPath Using AND and OR
The AND, and OR operators in the XPath selector in Selenium are used when locating a WebElement based on certain condition sets. In the case of AND, both conditions should be true. On the other hand, either of the two conditions can be true for OR in operator XPath.
Syntax of OR operator in XPath:
//input[@id='login_1' OR @name='login']
Syntax of AND operator in XPath:
//input[@id='login_1' AND @name='login']
starts-with() Method in XPath:
contains(), a highly useful technique in XPath that is especially used for handling WebElements with dynamically changing values.
The syntax for using the contains() method in XPath is:
//tagname[starts-with(@attribute,'starting name of the attribute value')]
Best Practices to Use Locators in Selenium WebDriver
Use a unique ID for element identification.
Avoid using IDs that change locations
Keep your locators short
Avoid elements that depend on auto-generated values
Don’t use XPath or CSS Selector provided by the developer tools
Avoid using the locators that change dynamically on page refresh : While working on some websites, it can be observed that the locators, such as ID or class name, change dynamically on page load or refresh. It should be noted that in such situations ID, class Name should not be used. Use CSS selector or Xpath.
Avoid using XPaths heavily in the project
Use explicit waits: Explicit waits in Selenium WebDriver should ensure that the WebElement is present and visible before the automated tests interact with that WebElement. This can help in avoiding test flakiness.
Comments