Monday, 17 March 2014

Xpath in selenium webdriver in Python - Example

Xpath is a standard technology to find the nodes in the webpage or xml file.
Below examples will give you idea about the xpath syntax.

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 2ndnext 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::*

Complete example of xpath using selenium webdriver in Python is given below



from selenium import webdriver

#driver = webdriver.Chrome("F:\\selenium\\Csharp\\iedriverserver.exe")

#driver = webdriver.Chrome("F:\\selenium\\Csharp\\chromedriver.exe")

driver = webdriver.Firefox()

driver.get("http://register.rediff.com/register/register.php")

try:
  
          driver.find_element_by_xpath("//input[@value='Check availability']").click()

   driver.close()

except Exception as e:

    print ("Exception occured", format(e));

finally:

    driver.quit()

    print ("finally")

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