Mastering XPath in Selenium with Python
๐ What is XPath?
XPath (XML Path Language) is a query language used to navigate through elements and attributes in an XML or HTML document. Selenium uses XPath to locate elements on a web page when other selectors like ID or class are not enough.
✅ Basic Setup with Selenium and Python
bash
Copy
Edit
pip install selenium
python
Copy
Edit
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://example.com")
# Example using XPath
element = driver.find_element("xpath", "//h1")
print(element.text)
driver.quit()
๐ Types of XPath
1. Absolute XPath
Navigates from the root node
Fragile and not recommended for dynamic content
xpath
Copy
Edit
/html/body/div[1]/section/h1
2. Relative XPath ✅ (Recommended)
Starts from a known element and is more stable
xpath
Copy
Edit
//div[@class='product']//h2
๐ง XPath Syntax Essentials
๐น Attributes
xpath
Copy
Edit
//input[@name='email']
๐น Text Matching
xpath
Copy
Edit
//button[text()='Submit']
๐น Contains (for partial matches)
xpath
Copy
Edit
//div[contains(@class, 'card')]
๐น Starts-with
xpath
Copy
Edit
//input[starts-with(@id, 'user')]
๐น Logical Operators
xpath
Copy
Edit
//input[@type='text' and @name='username']
๐งฉ Navigating the DOM
๐ธ Parent Node
xpath
Copy
Edit
//span[@class='price']/..
๐ธ Child Nodes
xpath
Copy
Edit
//div[@class='menu']/ul/li
๐ธ Following/preceding siblings
xpath
Copy
Edit
//label[text()='Email']/following-sibling::input
๐ Using XPath in Selenium Python
python
Copy
Edit
from selenium.webdriver.common.by import By
# Find element with XPath
element = driver.find_element(By.XPATH, "//button[contains(text(), 'Login')]")
element.click()
✅ You can also use find_elements(By.XPATH, ...) to get a list.
๐งช XPath Tips for Robustness
Prefer relative XPath
Avoid long, deeply nested paths
Use unique attributes, contains(), or indexed selections for dynamic pages
Use browser DevTools: right-click → Inspect → Copy XPath (but tweak it afterward)
๐ Example: Dynamic Table Row Selection
xpath
Copy
Edit
//table[@id='orders']//tr[td[text()='Order #12345']]/td[3]
This finds the 3rd column of the row where the first column contains "Order #12345".
๐ Advanced Use Cases
Click a button next to a specific label:
xpath
Copy
Edit
//label[text()='Username']/following::input[1]
Select the last item in a list:
xpath
Copy
Edit
//ul[@id='items']/li[last()]
๐ Resources for Practice
XPath Tester
Try XPath expressions directly in Chrome DevTools:
js
Copy
Edit
$x("//h1[contains(text(), 'Welcome')]")
Learn Selenium Python Training in Hyderabad
Read More
What are Locators in Selenium and How to Use Them
๐ Locating and Interacting with Web Elements
Setting Up Selenium in PyCharm or VS Code
Top Tools You Need to Start Selenium with Python
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment