How to find Elements by XPath using Selenium?

Find Elements by XPath

To find the HTML Elements by an XPath (language used for locating nodes in HTML) using Selenium in Python, call find_elements() method and pass By.XPATH as the first argument, and the XPath value as the second argument.

find_elements(By.XPATH, "xpath_value")

find_elements() method returns all the HTML Elements, that satisfy the given XPath value, as a list.

If there are no elements in the document for the given XPath value, then find_elements() method returns an empty list.


Consider the HTML document at the URL, with the following HTML content.

HTML Webpage

  <h2>Hello World</h2>
  <p>This is a paragraph.</p>
  <div name="xyz">Div 1</div>
  <div name="abc">Div 2</div>

In the following Python program, we will find all the div elements in the document using find_elements() method using the XPath value '/html/body/div'.

Python Program (Selenium)

from selenium import webdriver
from import ChromeDriverManager
from import Service as ChromeService
from import By

# Setup chrome driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

# Navigate to the url

# Find elements by XPath expression
my_elements = driver.find_elements(By.XPATH, '/html/body/div')
for element in my_elements:

# Close the driver


<div name="xyz">Div 1</div>
<div name="abc">Div 2</div>


In this Python Selenium tutorial, we learned how to find all the HTML elements by given XPath, in webpage, using Selenium.

Related Tutorials

Quiz on Selenium

Q1. What is Selenium Python used for?

Not answered

Q2. What is a web driver in Selenium Python?

Not answered

Q3. Which of the following is not a method to wait for a web element to load in Selenium Python?

Not answered

Q4. What is the method used to take a screenshot in Selenium Python?

Not answered

Q5. Which of the following is not a commonly used web element locator in Selenium Python?

Not answered
Code copied to clipboard successfully 👍