In this tutorial, we’ll explain how to locate elements on a web page and perform operations on it. To perform any automated action on a web page, finding locators is mandatory. These are unique identifiers associated with the web elements such as text, buttons, tables, div, etc.
Locate Elements using Selenium Python
Your automation script will fail to interact with the web page if it can’t find the web elements. Selenium Webdriver provides the following techniques for locating the web elements.
1. By Name
2. By ID
3. By Link Text
4. By Partial Link Text
5. By XPath
6. By CSS Selector
7. By Tag name
8. Locate Element by Classname
List of Python Methods to Find Locators
Let’s discuss each of them, one by one in detail. However, click the Selenium Python tutorial to return to the main topic.
Locate Elements by Name
It is a standard for web developers to define unique IDs for web elements in an HTML code. However, there may be cases when these unique identifiers are not present. Instead, the names are there; we can also use them to select a web element.
Here is a Python coding snippet to demonstrate the <find_element_by_name> method. This code opens Google in the browser and performs a text search.
from selenium import webdriver import time from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://google.com") driver.maximize_window() time.sleep(5) inputElement = driver.find_element_by_name("q") inputElement.send_keys("Techbeamers") inputElement.submit() time.sleep(20) driver.close()
If the HTML code has more than one web element with the “@name” attribute, this method will select the first web element from the list. If no match occurs, a NoSuchElementException gets raised.
Locate Elements by ID
This method should be used when the ID attribute for the element is available. It is the most reliable and fastest way to locate a particular web element on an HTML page. An ID will always be unique for any object on a web page. So, we should prefer using the Id attribute to locate the elements over other options.
Here is a coding snippet demonstrating the use of the <find_element_by_id> method. It also opens Google in the browser and performs a text search.
from selenium import webdriver import time from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://google.com") driver.maximize_window() time.sleep(5) inputElement = driver.find_element_by_id("lst-ib") inputElement.send_keys("Techbeamers") inputElement.submit() time.sleep(20) driver.close()
If more than one web elements have the same value of id, attribute, this method will return the first element for which the id matches. It will raise a NoSuchElementException if there is no match.
Locate Elements by Link Text
You should try this method for selecting hyperlinks from a web page. If the page has multiple elements with the same link text, it will locate the first element with a match. It works only on links (hyperlinks). That is why we call it the <Link Text locator>.
Here is another coding snippet showcasing the <find_element_by_link_text> method. The below code opens Google in the browser and performs a text search. After that, it opens a Hyperlink with link text as “Python Tutorial.”
from selenium import webdriver import time from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://google.com") driver.maximize_window() time.sleep(5) inputElement = driver.find_element_by_name("q") inputElement.send_keys("Techbeamers") inputElement.submit() time.sleep(5) elem = driver.find_element_by_link_text("Python Tutorial") elem.click() time.sleep(20) driver.close()
Locate Elements by Partial Link Text
Sometimes the exact link text can’t be used, yet your script has to locate the element. In such a case, you can use the partial link text method. It enables you to select a hyperlink by giving only a part of the link text.
Let’s modify the previous example to use the partial link text method. The updated code is as follows.
from selenium import webdriver import time from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://google.com") driver.maximize_window() time.sleep(5) inputElement = driver.find_element_by_name("q") inputElement.send_keys("Techbeamers") inputElement.submit() time.sleep(5) elem = driver.find_element_by_partial_link_text("Python") elem.click() time.sleep(20) driver.close()
This code opens the Python tutorial web page as in the above code.
Locate Elements by Xpath
Another useful method to locate an element is using an XPath expression. We use XPath when a proper ID or name attribute is missing on the web page.
XPath allows locating an element using the Absolute (not the preferred way), or the Relative XPath. Absolute XPaths determine the location of an object from the root (HTML). However, using Absolute XPath is not an efficient method.
It is because even if we make a small change in the web page code, absolute XPath will change. This will hinder the webdriver from locating the element with the old path.
In the case of Relative XPath, we try to locate a nearby element for which an id or name attribute is given (ideally a parent element). Now we can calculate the XPath of the target element relative to this nearby element. The chances of this XPath to change are very low, thus making our tests more robust.
Thus, both methods can help you locate the element having an id or name attribute.
XPath locators can also use attributes other than id and name for locating the element.
To understand the Absolute and Relative path, let’s take the following HTML code for user SignUp.
HTML code for User SignUp
<html> <body> <form id="signUpForm"> <input name="emailId/mobileNo" type="text" /> <input name="password" type="password" /> <input name="continue" type="submit" value="SignUp" /> <input name="continue" type="button" value="Clear" /> </form> </body> <html>
Now we will try locating different elements present on the page using XPath.
Here are the XPaths that will help Selenium Webdriver to locate the form element.
form_element = driver.find_element_by_xpath("/html/body/form[1]")
It is the Absolute path. It will fail if we make any changes to the HTML code.
Now, the following are the Relative Xpaths.
form_element = driver.find_element_by_xpath("//form[1]")
It marks the first form element.
form_element = driver.find_element_by_xpath("//form[@id='signUpForm']")
It uses the id attribute with the value “signUpForm” to locate the element.
We can locate the <emailId/mobileNo> element similarly.
email_input = driver.find_element_by_xpath("//form[input/@name='emailId/mobileNo']")
It will return the first form element having an ‘input’ child element. This input element has an attribute named ‘name’ and the value ’emailId/mobileNo’.
email_input = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]")
It will select the first ‘input’ child element of the ‘form’ element. Where the form element has the attribute named ‘id’ and the value ‘signUpForm’.
email_input= driver.find_element_by_xpath("//input[@name='emailId/mobileNo']")
It directly goes to the ‘input’ element having an attribute name with value as ’emailId/mobileNo’.
Locate Elements by CSS Selector
This method allows you to locate elements by class attribute name.
It will return the first element matching the input attribute. If the search fails, the method throws the NoSuchElementException.
For illustration, assume the below HTML code:
<html> <body> <div class="round-button">Click Here</p> </body> <html>
The above code has a single div element of the “round-button” class type. The below syntax represents the CSS selector for the “round-button” class.
div.round-button
Check this code. You can use it to locate the target div element following the CSS locator strategy.
get_div = driver.find_element_by_css_selector('div.round-button')
By Tag Name
This is another method you can explore to find a web element. It needs the tag name.
It will return the first element having the specified name. If the search doesn’t succeed, the method will throw the NoSuchElementException.
For illustration, assume the below HTML code:
<html> <body> <title>Hello Python</title> <p>Learn test automation using Python</p> </body> <html>
The above code has a title tag with some text. You can find it using the below code.
get_div = driver.find_element_by_tag_name('title')
By Class Name
This method allows you to locate elements based on the class name.
It will return the first element with the given class name. If the search doesn’t succeed, the method will throw the NoSuchElementException.
For illustration, assume the below HTML code:
<html> <body> <div class="round-button">Click Here</div> </body> <html>
The above code has a class with a name. You can find it using the below code.
get_div = driver.find_element_by_class_name('round-button')
Before You Leave
Today, you learned eight locator types and how to use them in Selenium Python. Keep following the examples in the tutorial and practice with each locator to find elements.
Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.
Enjoy testing,
TechBeamers.