How to find the Parent Element in a page using Python Selenium WebDriver

This is a quick article to show how you can easily get the parent element of an HTML element using Selenium Webdriver with Python. There is more than one way.

Let’s suppose that we want to get an HTML button that has no id or unique CSS class from within an HTML page:

<html>
<body>
...
  <button>
   <span id="account-login-submit-message">Login</span>
  </button>
...
</body>
</html>

1. Getting Parent element using XPATH ..

First, we can retrieve the HTML Element for the <span> tag using the id:

submitLoginSpan = wd.find_element_by_id("account-login-submit-message")

Then you can retrieve the parent element using XPATH by simply calling:

submitLoginSpan = wd.find_element_by_id("account-login-submit-message")
submitLoginButton = submitLoginSpan.find_element_by_xpath("..")
submitLoginButton.click()

2. Getting Parent Element directly using XPATH ancestor

We can also etrieve the parent element of an element using XPATH :ancestor::<TAG_NAME>. Where the TAG_NAME Is the name of the tag of the HTML Element that we are trying to retrieve.

submitLoginButton = wd.find_element_by_xpath('//span[@id="account-login-submit-message"]/ancestor::button')
submitLoginButton.click()

3. Getting Parent Element using CSS Selector

Currently, there is no way of selecting a parent element using a CSS Selector, hence I included it here to shorten your search.

4. Getting Parent Element using element.parent

You might be tempted to write the following code:

submitLoginSpan = wd.find_element_by_id("account-login-submit-message")
submitLoginButton = submitLoginSpan.parent
submitLoginButton.click()

But you will get an error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_27716/2471411830.py in <module>
      1 submitLoginSpan = wd.find_element_by_id("account-login-submit-message")
      2 submitLoginButton = submitLoginSpan.parent
----> 3 submitLoginButton.click()

AttributeError: 'WebDriver' object has no attribute 'click'

This is because the .parent attribute returns a reference to Selenium WebDriver instance that contains this HTML Element. It is not returning the actual parent HTML Element


Posted

in

,

by