find out all child elements xpath from parent xpath using selenium webdriver in python
Asked Answered
A

2

12

I can find the element by xpath of driver.find_element_by_xpath('//*[@id="app"]/table/tbody/tr[1]/td[1]'). but any way i can return all children elements like tag and tag xpath?

<tr>
    <td class="">
        <div>
            <a href="/user/1">
                <!-- react-text: 6011 -->user first name |
                <!-- /react-text -->
                <!-- react-text: 6012 -->
                <!-- /react-text -->
                <!-- react-text: 6013 -->user last name
                <!-- /react-text -->
            </a>
            <div>
                <span>
            <!-- react-text: 6014 -->town<!-- /react-text -->
            <!-- react-text: 6015 -->  | <!-- /react-text -->
            <!-- react-text: 6015 -->month<!-- /react-text -->
            <!-- react-text: 6081 --> | date<!-- /react-text -->
            <!-- react-text: 6082 -->year<!-- /react-text -->
            </span>
            </div>
        </div>
    </td>
    <td class=""><a href="/address/1">1</a>
        <div class="">city</div>
    </td>
</tr>
Aweather answered 18/4, 2017 at 17:47 Comment(1)
Just to clarify, you need all the child elements of current WebElement?Omnipresent
O
20

The key is to use the xpath .//* to get all the children for current node. The . picks the current element & //* selects all the elements, which makes the whole xpath to select all child elements of current element. Your code will look like this:

parent_elem = driver.find_element_by_xpath('//*[@id="app"]/table/tbody/tr[1]/td[1]')
child_elements = parent_elem.find_elements_by_xpath('.//*')
Omnipresent answered 18/4, 2017 at 18:1 Comment(2)
i am able to find all child_elements, however, I would like to have something like a list contains all child element xpath [ <child 1 xpath>, <child 2 xpath>, ..]Aweather
There really is no generic way of fetching a xpath because there is no 1 xpath for an element. There can be many ways to get an elements xpath.Omnipresent
A
3

if you need to find immediate children, use

child_elements = parent_elem.find_elements_by_xpath('./*')
Acentric answered 13/5, 2022 at 21:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.