TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: How to Locate Elements using Selenium Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python SeleniumPython Tutorials

How to Locate Elements using Selenium Python

Last updated: Feb 24, 2024 10:45 pm
By Meenakshi Agarwal
Share
10 Min Read
Locate Elements using Selenium Python
SHARE

In this tutorial, we’ll explain how to locate elements on a web page and perform operations on it.

Contents
1. Locate Elements by Name2. Locate Elements by ID3. Locate Elements by Link Text4. Locate Elements by Partial Link Text5. Locate Elements by XpathHTML code for User SignUp6. Locate Elements by CSS Selector7. By Tagname8. By Classname

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

Locate Elements using Selenium Python

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

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

TAGGED:Selenium Locate Elements
Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Merge Multiple CSV Files in Python Merge Multiple CSV Files using Python I/O
Next Article Selenium WebDriver Waits in Python Explained with Examples Use Selenium WebDriver Waits in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x