...
......

Get grandParent using xpath in selenium webdriver

<div class="myclass">
  <span>...</span>
  <div>
       <table>
              <colgroup>...</>
              <tbody>
                    <tr>...</tr>
                    <tr>
                         <td> 
                              <input ...name="myname" ...> 
                         </td>
                    </tr>
                    <tr>...</tr>
              <tbody>
       </table>
  </div>

</div>

this is my html code ... I have the attribute "name" .. so I can access the tag ... but from this line I want to access the top element. One way is that I write driver.find_element_by_xpath('..')6-7 times to get this parent, but I don't know how many steps I have to complete above. I just want an xpath expression or similar thing to have access to the top.

I am using selenium webdriver with python

+3
source share
4 answers

Instead of aiming at an element of a deeper level and climbing in a tree, you can select an element of a higher level and check the attribute of the descendant node:

.//div[@class="myclass"][.//input[@name="myname"]]
+10

@Paul input div , , , :

//input[@name='myname']/ancestor::div[@class = 'myclass']
+4

I agree with StuartLC, but would change that to

 //input[@name='myname']/ancestor::div[contains(@class,'myclass')]

I always used the 'contains' attribute in a class, since a class can contain multiple values, but unlike CSS selectors, Xpath treats it as a literal string.

T. StutartLC xpath will fail if in a div

another class will be added,

Alternatively, if you want to find it from the 'myname' element, you can use;

self::*/ancestor::div[contains(@class,'myclass')]
+2
source
grandparent = element.find_element_by_xpath('../..')
0
source

All Articles