0
0
Selenium Pythontesting~5 mins

Find element by XPath in Selenium Python

Choose your learning style9 modes available
Introduction

We use XPath to find elements on a web page when other methods like ID or class name are not enough or available.

When the element has no unique ID or class.
When you want to find elements based on their position or text.
When you need to navigate complex HTML structures.
When testing dynamic web pages where element attributes change.
When you want to find elements with specific attribute values.
Syntax
Selenium Python
element = driver.find_element(By.XPATH, 'xpath_expression')

Use By.XPATH to specify you want to find by XPath.

The xpath_expression is a string that describes the path to the element.

Examples
Finds a button element with the ID 'submit'.
Selenium Python
element = driver.find_element(By.XPATH, '//button[@id="submit"]')
Finds a div element that contains the exact text 'Welcome'.
Selenium Python
element = driver.find_element(By.XPATH, '//div[text()="Welcome"]')
Finds an input element with type 'text' and name 'username'.
Selenium Python
element = driver.find_element(By.XPATH, '//input[@type="text" and @name="username"]')
Sample Program

This script opens a simple page with a button, finds the button using XPath, prints its text, and closes the browser.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By

# Setup WebDriver (make sure the driver is in PATH)
driver = webdriver.Chrome()

# Open a simple test page
html = '''<html><body><button id="submit">Submit</button></body></html>'''

# Load the HTML content using data URL
driver.get("data:text/html;charset=utf-8," + html)

# Find the button by XPath
button = driver.find_element(By.XPATH, '//button[@id="submit"]')

# Print the button text
print(button.text)

# Close the browser
driver.quit()
OutputSuccess
Important Notes

XPath expressions can be absolute (starting from root) or relative (starting from anywhere).

Using XPath can be slower than other locators, so use it only when needed.

Always test your XPath in browser DevTools before using it in code.

Summary

XPath helps find elements when other locators are not enough.

Use driver.find_element(By.XPATH, 'xpath') to find one element.

Test XPath expressions carefully to avoid errors.