How to get the parent element in Selenium Python?

Selenium Python – Get the parent element

In this tutorial, you will learn how to get the parent element of a given element, in Selenium Python.

To get the parent element of a given element in Selenium Python, call the find_element() method on the given element and pass By.XPATH for the by parameter, and '..' for the value parameter in the function call.

If myelement is the WebElement object for which we would like to find the parent, the code snippet for find_element() method is

myelement.find_element(By.XPATH, '..')

Example

In this example, we shall consider loading the webpage at URL: https://pythonexamples.org/tmp/selenium/index-19.html. The contents of this HTML file is given below.

The webpage contains a parent div with three children divs.

<html>
 <body>
  <h1>Hello Family</h1>
  <div id="parent">
    <div id="child1">This is child 1.</div>
    <div id="child2">This is child 2.</div>
    <div id="child3">This is child 3.</div>
  </div>
 </body>
</html>
Copy
Selenium Python - Get parent element - Webpage

We shall take the first child div#child1 as our WebElement of interest, and find its parent div. We shall take the screenshot of the first child, and the parent.

Python Program

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By

# Setup chrome driver
driver = webdriver.Chrome(service= ChromeService(executable_path=ChromeDriverManager().install()))
driver.set_window_size(500, 400)

# Navigate to the url
driver.get('https://pythonexamples.org/tmp/selenium/index-19.html')

# Get the div element you are interested in
mydiv = driver.find_element(By.ID, 'child1')

# Get parent of mydiv
parent = mydiv.find_element(By.XPATH, '..')

# Take sceenshots of mydiv, and its parent
mydiv.screenshot('screenshot-1.png')
parent.screenshot('screenshot-2.png')

# Close the driver
driver.quit()
Copy

Screenshot of child div element

Python Selenium - Screenshot of child div

Screenshot of parent div element

Python Selenium - Screenshot of parent div

Summary

In this Python Selenium tutorial, we have given instructions on how to find the parent element of a given web element, with the help of an example program.

Related Tutorials

Quiz on Selenium

Q1. What is Selenium Python used for?

Not answered

Q2. What is a web driver in Selenium Python?

Not answered

Q3. What is the method used to navigate back to the previous page in Selenium Python?

Not answered

Q4. Which of the following is not a commonly used web element locator in Selenium Python?

Not answered

Q5. What is the method used to select a value from a drop-down list in Selenium Python?

Not answered
Code copied to clipboard successfully 👍