XPath for parent element in Selenium


Python Selenium - XPath for parent element

The XPath expression to get the parent element of a given element is

".."

XPath for parent when element is already there

For example, a web element myelement is already there, and you want to get the parent element of this myelement using XPath, then use the following code.

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

Consider the following HTML code.

<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>

If myelement is the element with id value is equal to child1, child2, or child3, then its parent element is the div with id="parent".

XPath for parent when element's id is given

For example, you know only the id of the web element, say myid, and you would like to get the parent element of this myelement using XPath, then use the following code.

driver.find_element(By.XPATH, "//*[@id='myid']/..")

Replace 'myid' with the value of the id attribute, whose parent you want to find out.

//*[@id='myid'] selects the node, / is the XPath expression separator, and .. selects the parent of the node.

Similarly, if any other attribute or locator is given for you to identity the element, you can respective expression to find the node of interest, and then write the parent selector operator .., joined by XPath expression separator /.

Consider the following HTML code.

<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>

Suppose, we would like to get the parent element of the element whose id is "child2". Then the code for finding the parent element using XPath is as shown in the following.

parent_element = driver.find_element(By.XPATH, "//*[@id='child2']/..")

Tutorial

Please refer this tutorial Selenium - Get parent element for an example on how to get a parent element for a given div element using XPath.

Summary

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