XPath for all child elements in Selenium Python

Python Selenium – XPath for all child elements

The XPath operator to get all the child elements of a given element is

"*"

XPath for child elements when element is given

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

myelement.find_elements(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>
Copy

If myelement is the element with id value equal to "parent", then the child elements are the #child1, #child2, and #child3.

XPath for child elements 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 all the child elements of this element using XPath, then use the following code.

driver.find_elements(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 whose id is 'myid', / is the XPath expression separator, and * selects all the child elements of this node.

Similarly, if any other attribute or locator is given for you to identity the element, you can modify the expression to find the node of interest, and then write the children 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>
Copy

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

children = driver.find_elements(By.XPATH, "//*[@id='parent']/*")

Tutorial

Please refer this tutorial Selenium – Get all child elements for an example on how to get the child elements for a given element using XPath.

Summary

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

Quiz on Selenium

Q1. What is the method used to find web elements in Selenium Python?

Not answered

Q2. What is the method used to interact with web elements in Selenium Python?

Not answered

Q3. Which of the following is not a commonly used assertion method 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 👍