XPath Basics for Selenium
What Is XPath?
XPath is a language for navigating the HTML tree. It is more powerful than CSS because it can match text, move up to parents and use conditions. Use it with By.XPATH.
Absolute vs Relative
| Type | Example | Problem |
|---|---|---|
Absolute (starts with /) | /html/body/div[2]/form/input[1] | Breaks when anything in the page structure changes. Avoid |
Relative (starts with //) | //input[@id='username'] | Searches anywhere. Use this |
Basic Syntax
text
//tagname[@attribute='value']
//input[@id='username'] input whose id is username
//*[@id='username'] any tag with that id
//a[@href='/login']
//button[@type='submit']
python
driver.find_element(By.XPATH, "//input[@name='username']")
driver.find_element(By.XPATH, "//button[@type='submit']").click()
Matching Text
text
//button[text()='Login'] exact text
//a[contains(text(),'Forgot')] contains
//h2[normalize-space()='Login Page'] ignores extra spaces (safer)
//*[contains(., 'Welcome')] text anywhere inside the element
python
driver.find_element(By.XPATH, "//a[text()='Checkboxes']").click()
driver.find_element(By.XPATH, "//a[contains(text(),'Drop')]")
contains() and starts-with()
Use them when ids or classes change partly, such as id="btn_3829".
text
//input[contains(@id,'user')]
//div[starts-with(@id,'item_')]
//a[contains(@class,'nav-link')]
Class matching:
@class='btn primary' must match the whole string and order. contains(@class,'primary') is more reliable.
Multiple Conditions
text
//input[@type='text' and @name='email']
//button[@type='submit' or @id='go']
//input[not(@disabled)]
Position and Index
text
(//input[@type='checkbox'])[1] first checkbox in the whole page
(//input[@type='checkbox'])[last()] last
//table//tr[3] third row (XPath index starts at 1!)
//ul/li[position()<=3] first three items
Index starts at 1 XPath counts from 1, not 0, unlike Python lists.
Wildcards
text
//*[@id='main'] any tag
//*[@*='login'] any attribute equal to login (slow, use rarely)
Practice Example
python
driver.get("https://the-internet.herokuapp.com/login")
driver.find_element(By.XPATH, "//input[@id='username']").send_keys("tomsmith")
driver.find_element(By.XPATH, "//input[@id='password']").send_keys("SuperSecretPassword!")
driver.find_element(By.XPATH, "//button[contains(.,'Login')]").click()
msg = driver.find_element(By.XPATH, "//div[@id='flash' and contains(@class,'success')]").text
print(msg)
Test XPath in the Browser
- Chrome DevTools Elements tab: Ctrl+F and paste the XPath, the count is shown (1 of 1 is ideal)
- Console:
$x("//input[@id='username']")returns the matches
Write XPath short: Pick the smallest unique expression.
//button[text()='Save'] is better than a long chain of parents.
Conclusion
Use relative XPath that starts with //. Match by attribute, text() or contains(), combine conditions with and/or and remember that XPath positions start at 1.
Quick Summary: //tag[@attr='v'], text(), contains(), (…)[n], never absolute paths.

