The Ultimate Cheat Sheet on XPath in Python

XPath aka XML path language defined by W3C is used to traverse through the elements in the XML document.
Its like a query language to search element(nodes) by a variety of criteria in XML document.

XPath is widely used by Testers in Selenium framework with Python to find the elements in the HTML document.

Lets see  what all the things we can do with XPath to find elements in an HTML document. In the below table, I have added column Type, Searched Element with thier respective XPath at the end. Assuming the “x” is the tag. e.g <input name=”text value” />, So x=input and A=name.


TypeSearch for Web ElementXPath
TagWeb Element <x> by relative reference//x
Web Element <x> with attribute A value ‘t’//x[@A=’t’]
Web Element <x> with attribute A containing text ‘t’//x[contains(@A, ‘t’)]
Web Element <x> whose attribute A begins with ‘t’//x[starts=with(@A, ‘t’)]
Web Element <x> whose attribute A ends with ‘t’//x[ends—with(@A, ‘t’)]
Web Element <x> with attribute A containing exactly text ‘t’ and attribute B containing exactly text ‘v’//x[contains(@A, ‘t’) and contains(@B,‘v’)]

In the above Image
I have used //x[@A=’t’] as //input[@name=’firstName’] as XPath.You can try above mentioned XPath in the Firefox with FirePath’s console installed. Now, lets see how we can implement this Web Element XPath’s in Selenium test case with Python to enter the value in it(input text box).





ID & Name

Web Element <E> with id ‘I’,
All Web Elements with id ‘I’
Web Element <X> with name‘N’
All Web Elements with name‘N’
All Web Elements with id ‘I’ or name ‘N’
//*[@id=’I’ or @name=’N’]


Web Element <X> with a class C



All Elements with text ‘t’ exactly


Child or subChild

Element <F> which is a child or a subchild of Element <X>



Ref. : Gabiste Akoua thanks for being my mentor

Let me know your thoughts regarding the post by commenting below.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.