How will you travel from child to parent with xpath in Selenium with python?


We can identify a parent from its children in DOM with the help of xpath. There are situations where we have dynamic attributes for the parent node in html but the child nodes have unique static attributes for identification.

This can be achieved with the help of relative xpath along with the parent xpath axe. Method.

Syntax 

driver. find_element_by_xpath("//input[@id='job']/parent::div")

Example

Code Implementation for child to parent traversal.

from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/tutor_connect/index.php")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of xpath parent
atb=driver.find_element_by_xpath ("//input[@id='txtSearchText']/parent::div")
#prints the class attribute value in console
val = atb.get_attribute("class")
print(val)
driver.close()

Updated on: 29-Jul-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements