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.
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).
Ref. : Gabiste Akoua thanks for being my mentor
Let me know your thoughts regarding the post by commenting below.
[mc4wp_form]
| Type | Search for Web Element | XPath |
| Tag | Web 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’)] |
__author__ = 'WP8Dev'
import unittest
from selenium import webdriver
class SearchTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver = webdriver.Firefox()
cls.driver.implicitly_wait(20)
cls.driver.maximize_window()
cls.driver.get("http://demoaut.com/mercuryregister.php")
def test_1(self):
self.driver.find_element_by_xpath("//input[@name='firstName']").send_keys("Pramod")
self.assertTrue(self.driver.find_element_by_xpath("//input[@name='firstName']").is_displayed())
@classmethod
def tearDownClass(cls):
cls.driver.quit()
if __name__ == "__main__":
unittest.main(verbosity=2)
|
ID & Name 🎭 Want to master this with real projects? Join the Playwright Automation Mastery course at The Testing Academy. |
|
|
||||||||||
|
Class |
Web Element <X> with a class C |
//X[@class=’C’] |
||||||||||
|
Text |
|
//*[.=’t’] |
||||||||||
|
Child or subChild |
Element <F> which is a child or a subchild of Element <X> |
//X//F |
🎓 Master Playwright End to End
Join hundreds of SDETs building real automation frameworks. Lifetime access, hands-on projects, and a job-ready portfolio.
