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
4 answers
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