Selenium web element locating strategy using xpath.

Common xpath selector

  • Absolute reference and child reference with “/”
xpath=/html  # starting from root
xpath=./div  # child div of current element
xpath=/html/body
  • Relative reference and descendant reference with “//”
xpath=//input    # any input in whole dom
xpath=.//input   # any input from current location
xpath=//div//input # input is descendant of div
xpath=//div/input  # input is child of div
  • Parent element with parent:: and ..
xpath=//div[@id='foo']/parent::div
xpath=//div[@id='foo']/../../div
  • Any element and any attribute
xpath=//div/input[@type='text']/*
xpath=//*[text()='foo']
xpath=//div[@*='foo']
  • Attribute and attribute value with “@”
1) has attribute:
xpath=//div[@attr]
2) attribute value match:
xpath=//div[@attr='foo']
3) attribute value contains:
xpath=//div[contains(@attr, 'foo')]
4) attribute value starts with:
xpath=//div[starts-with(@attr, 'foo')]
NOTE: ends-with not supported.
  • Multiple attributes or conditions
xpath=//div[@attrA='foo' and @attrB='bar']
xpath=//div[@attrA='foo'][@attrB='bar']
xpath=//div[starts-with(@attrA, 'foo')][contains(@attrB, 'bar')]
xpath=//div[starts-with(@attrA, 'foo') or contains(@attrB, 'bar')]
xpath=//div[starts-with(@attrA, 'foo') and contains(@attrB, 'bar')]
  • Inner text with text()
xpath=//div[text()='foobar']
xpath=//div[contains(text(), 'foo')]
  • Index with [] and position()
xpath=//input[n]
xpath=//input[last()]
xpath=//input[last()-1]
xpath=//div/div[position()=2]
  • Child count with count(*)
xpath=//div[count(*)=0]  # no child
xpath=//div[count(*)=1]  # only 1 child
xpath=//div[count(*)>2]  # more than 2 children
  • Sibling
xpath=//div[@id='foo']/div[@class]/following-sibling::div
xpath=//div[@id='foo']/div[@class]/preceding-sibling::div
  • Nesting condition
xpath=//div[@id='foo']/div[p]  # has p child
xpath=//div[@id='foo']/div[following-sibling::div[@id='bar']]
xpath=//div[@id='foo']//div[div[@class='bar']]

References

BACK TO TOP
Post tagged with: selenium, webdriver, xpath, automation