0
0
Selenium-pythonHow-ToBeginner · 3 min read

How to Find Element by XPath in Selenium: Simple Guide

In Selenium, you find an element by XPath using driver.find_element(By.XPATH, "xpath_expression"). This method locates the element matching the XPath string you provide, allowing you to interact with it in your test scripts.
📐

Syntax

The basic syntax to find an element by XPath in Selenium is:

  • driver.find_element(By.XPATH, "xpath_expression"): Finds the first element matching the XPath.
  • driver.find_elements(By.XPATH, "xpath_expression"): Finds all elements matching the XPath as a list.
  • By.XPATH: Specifies that the locator strategy is XPath.
  • "xpath_expression": The XPath string that describes the element's location in the HTML.
python
from selenium import webdriver
from selenium.webdriver.common.by import By

# Initialize the driver (example with Chrome)
driver = webdriver.Chrome()

# Find a single element by XPath
element = driver.find_element(By.XPATH, "//tagname[@attribute='value']")

# Find multiple elements by XPath
elements = driver.find_elements(By.XPATH, "//tagname")
💻

Example

This example opens a webpage and finds a button by its XPath, then clicks it. It shows how to use find_element with XPath in a real test scenario.

python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import time

# Setup Chrome options
options = Options()
options.add_argument('--headless')  # Run browser in headless mode

# Setup Chrome driver service
service = Service()

# Initialize driver
driver = webdriver.Chrome(service=service, options=options)

try:
    # Open example page
    driver.get('https://www.w3schools.com/html/html_forms.asp')

    # Find the "Submit" button by XPath
    submit_button = driver.find_element(By.XPATH, "//button[text()='Submit']")

    # Click the button
    submit_button.click()

    print("Button found and clicked successfully.")
finally:
    driver.quit()
Output
Button found and clicked successfully.
⚠️

Common Pitfalls

Common mistakes when using XPath in Selenium include:

  • Using absolute XPath (starting from /html) which breaks easily if page structure changes.
  • Incorrect XPath syntax causing NoSuchElementException.
  • Not waiting for elements to load before searching, leading to errors.
  • Using find_element when multiple elements match, causing unexpected results.

Always prefer relative XPath starting with // and use explicit waits.

python
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Wrong way: absolute XPath (fragile)
# element = driver.find_element(By.XPATH, "/html/body/div[2]/button")

# Right way: relative XPath with wait
wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.XPATH, "//button[text()='Submit']")))
📊

Quick Reference

Here is a quick reference for XPath locator usage in Selenium:

XPath ExpressionDescriptionExample
//tagnameSelects all elements with the tag name//input
//tagname[@attr='value']Selects elements with attribute value//button[@id='submit']
//tagname[text()='text']Selects elements with exact text//a[text()='Home']
//tagname[contains(@attr, 'value')]Selects elements where attribute contains value//div[contains(@class, 'header')]
(//tagname)[index]Selects element at position index (1-based)(//input)[2]

Key Takeaways

Use driver.find_element(By.XPATH, "xpath_expression") to locate elements by XPath in Selenium.
Prefer relative XPath expressions starting with // for more robust tests.
Use explicit waits to ensure elements are present before interacting.
Avoid absolute XPath as it breaks easily with page changes.
Use find_elements when expecting multiple matches to avoid errors.