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.
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’)] |
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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | __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 |
|
| ||||||||||
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 |
Ref. : Gabiste Akoua thanks for being my mentor
Let me know your thoughts regarding the post by commenting below.
[mc4wp_form]