How to find parent elements by python webdriver?

SeleniumAutomation TestingTesting Tools

We can find parent elements with Selenium webdriver. First of all we need to identify the child element with help of any of the locators like id, class, name,xpath or css. Then we have to identify the parent element with the find_element_by_xpath() method.

We can identify the parent from the child, by localizing it with the child and then passing (..) as a parameter to the find_element_by_xpath().

Syntax−

child.find_element_by_xpath("..")

Let us identify class attribute of parent ul from the child element li in below html code−

The child element with class heading should be able to get the parent element having toc chapters class attribute.

Example

from selenium import webdriver
driver = webdriver.Chrome(executable_path="
C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify child element
l= driver.find_element_by_xpath("//li[@class='heading']")
#identify parent from child element with (..) in xpath
t= l.find_element_by_xpath("..")
# get_attribute() method to obtain class of parent
print("Parent class attribute: " + t.get_attribute("class"))
driver.close()

Output

raja
Published on 18-Sep-2020 09:13:14
Advertisements