In this tutorial, we’ll explain how to locate elements on a web page and perform operations on it.
If you want to perform any automated action on a web page, you’ll need the locators from it. These are unique identifiers associated with the web elements such as text, buttons, tables, div, etc.
It is not possible to interact with the web page if the test script is not able to find the web elements. Selenium Webdriver provides the following techniques for locating the web elements.
Click here to Go Back to main Selenium Python tutorial.
1. By Name
2. By ID
3. By Link Text
4. By Partial Link Text
5. By XPath
6. By CSS Selector
7. By Tagname
8. Locate Element by Classname
Let’s discuss each of them, one by one in detail.
How to Locate Elements using Selenium Python with Examples
1. Locate Elements by Name
It is a standard practice 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; then we can also use them to select a web element.
Here is the code snippet that demonstrates the use of <find_element_by_name> method. Below 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 “@name” attribute, then this method will select the first web element from the list. If no match occurs, a NoSuchElementException gets raised.
2. Locate Elements by ID
We use this method when the Id attribute for the element is available. It is in fact, the most reliable and the 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 Id attribute for locating the elements over other available options.
Here is the code snippet that demonstrates the use of the <find_element_by_id> method. Below 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_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.
3. Locate Elements by Link Text
We use this method for selecting hyperlinks from a web page. If multiple elements have the same link text, then this method selects the first element with a match. It works only on links (hyperlinks), that is why we call it <Link Text locator>.
Here is the code snippet that demonstrates the use of <find_element_by_link_text> method. 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()
4. Locate Elements by Partial Link Text
For locating the element by using the link text method, we need to provide the complete Link text. However, the partial link text method enables us to select a hyperlink by giving only a part of the link text.
In the above example if we use the partial link text method, then the code will become as.
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.
5. 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 not present in the code to access that element.
XPath allows locating an element using the Absolute (not the preferred way), or the Relative XPath. Absolute XPaths determines the location of an object from the root (html). However, using Absolute XPath is not an efficient method.
It is because if we make even a slight change in the web page code. Absolute XPath will change, and the webdriver may not be able to locate the element with the old one.
In 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 is very less, thus making our tests more robust.
Thus, both of these ways help us to locate an element that does have 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 do any change to the HTML code.
Now 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 value as “signUpForm” to locate the element.
We can locate <emailId/mobileNo> element in similar manner as.
email_input = driver.find_element_by_xpath("//form[input/@name='emailId/mobileNo']")
It will return the first form element having ‘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’.
6. 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 “round-button” class type. To access a CSS class, you can use dot (.) symbol. The below syntax represents the CSS selector for the “round-button” class.
div.round-button
With the below code, you can locate the target div element following the CSS locator strategy.
get_div = driver.find_element_by_css_selector('div.round-button')
7. By Tagname
This method allows you to find a web-element by specifying 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')
8. By Classname
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')
Conclusion
We hope that you now know how to use the locators and find elements using them.
If you indeed have learned from this class, then care to share it with your colleagues. Also, connect to our social media accounts to receive timely updates.
Best,
TechBeamers