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.

Example

Let us consider the below web document.

index.html

<html>
 <body>
  <p>Paragraph 1</p>
  <div name="xyz">Div 1</div>
  <div name="abc">Div 2</div>
 </body>
</html>

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.webdriver.chrome.service import Service
from selenium import webdriver
from selenium.webdriver.common.by import By

service = Service(executable_path="/usr/local/bin/chromedriver")
#initialize web driver
with webdriver.Chrome(service=service) as driver:
    #navigate to the url
    driver.get('http://127.0.0.1:5500/localwebsite/index.html')
    #find elements by xpath
    elements = driver.find_elements(By.XPATH, '/html/body/div')
    for element in elements:
        print(element.get_attribute("outerHTML"))

Output

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

Summary

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