TAGS :Viewed: 5 - Published at: a few seconds ago

[ 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 attribute "name" ..so I can access tag ...but from this line I want to access top element. One way is that I write driver.find_element_by_xpath('..') 6-7 times to get that parent but I dont know how many steps I have to go above. I simply want a xpath expression or similar thing to access top .

I'm using Selenium webdriver with python

Answer 1


Instead of targeting a deeper level element and going up in the tree, you can select the higher level element and test for a descendant node attribute:

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

Answer 2


As an alternative to @Paul's answer, you can navigate up from the input to the div via the ancestor axis, however, I can't see why his solution wouldn't work for you:

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

Answer 3


I agree with StuartLC BUT would change it to;

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

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

ie. StuartLC's xpath would fail if another class was added to the div

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

self::*/ancestor::div[contains(@class,'myclass')]