Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 385
jacobcan118 Avatar asked Apr 18 '17 17:04

jacobcan118


People also ask

How do you get children of elements in Selenium?

We can locate child nodes of web elements with Selenium webdriver. First of all we need to identify the parent element with help of any of the locators like id, class, name, xpath or css. Then we have to identify the children with the findElements(By. xpath()) method.

Where is parent child XPath in Selenium?

XPath(Current node): //input[@id = 'text']. We will then find the XPath of the parent element node of the current node using parent syntax, as shown below screenshot. XPath of the Parent node: //input[@id = 'text']//parent::span. It will then select the parent node of the input tag having Id = 'text'.


1 Answers

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('.//*')
like image 56
Jayesh Doolani Avatar answered Sep 20 '22 14:09

Jayesh Doolani