Friday, 14 February 2014

How to identify the elements using xpath in Selenium Webdriver?

In this article I am going to explain you how we can use xpath to identify the web elements using selenium web driver.

What is xpath in selenium web driver?

xpath is used to find the specific element in the given webpage.
Some of the below examples will demonstrate how we can write the xpath expressions.

Find all elements with tag input
//input
Find all input tag element having  attribute type = ‘hidden’
//input[@type='hidden']
Find all input tag element having  attribute type = ‘hidden’  and name attribute = ‘ren’
//input[@type='hidden'][@name='ren']
Find all input tag element with attribute type containing ‘hid’
//input[contains(@type,'hid')]
Find all input tag element with attribute type starting with ‘hid’
//input[starts-with(@type,'hid')]
Find all elements having innertext = ‘password’
//*[text()='Password']
Find all td elements having innertext = ‘password’
//td[text()='Password']
Find all next siblings of td tag having innertext = ‘gender’
//td[text()='Gender']//following-sibling::*
Find all elements in the 2nd next sibling of td tag having innertext = ‘gender’
//td[text()='Gender']//following-sibling::*[2]//*
Find input elements in the 2nd next sibling of td tag having innertext = ‘gender’
//td[text()='Gender']//following-sibling::*[2]//input
Find the td which contains font element containing the text ‘12’
//td[font[contains(text(),'12')]]
Find all the preceding siblings of the td which contains font element containing the text ‘12’
//td[font[contains(text(),'12')]]//preceding-sibling::*
Find the second td ancestor of the span element containing text - Exp Date then find the previous td element’
//span[text()='Exp Date']//ancestor::td[2]//preceding-sibling::td
Find the first td ancestor of the span element containing text - Exp Date then find the previous td element
//span[text()='Exp Date']//ancestor::td[1]//preceding-sibling::td
Find the element containing specific text
//p[text()[contains(.,'refer')]]



Below example shows how to use logical operators (and / or / not) in XPATH.

//div[contains(@class,'result-row') and not (contains(@style,'none'))]

Below example shows how to handle the quote inside text

//label[contains(text(),"Killer\'s age.")]


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

No comments:

Post a Comment

Buy Best Selenium Books

Contributors