Skip to content

xpath

Sources : https://www.guru99.com/xpath-selenium.html

Here is the general structure:

  • // : the start node: // is relative, / is absolute
  • tagname : input,div, img, etc
  • @attribute : optional attribute name : @type, @href, etc
  • = : what do you think ?
  • 'value' : the attributes value : 'text', 'http://localhost', etc

Absolute paths start from the root, so some examples in selenium

selenium
1
2
3
find_elements_by_xpath("/html")
find_elements_by_xpath("/html/*")
find_elements_by_xpath("/html/body/div[2]")

Examples of possible result arrays :

  • 1 element : [html]
  • 2 elements : [head,body]
  • 1 element : [div]

Relative paths start with '//' and it just means 'start anywhere in the document'. It does not mean there is a 'current' node.

So when searching you would have to do something like this in absolute and relative path :

paths
1
2
3
4
# need exact depth for this :
/html/*/*/*/*/[contains(text(),'Inloggen')
# but ... much easier :
//[contains(text(),'Inloggen')

You can play around with xpath in the development console of chrome. Select the elements tab and underneath is a text input that accepts xpath.

It will highlight hat it finds in the main tab if you hit return. Start with "/html" to get the feeling. In this search you can use expressions like '/html///div' which don't seem to work in selenium find_elements_by_xpath().

attributes


all divs containing w2ui in the class //div[contains(@class,'w2ui')] all elements with Inloggen in the text //[contains(text(),'Inloggen')] all elements with Inloggen in the value //[contains(text(),'Inloggen')]