Get grandParent using xpath in selenium webdriver

空扰寡人 提交于 2020-02-22 05:50:47

问题


<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


回答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"]]



回答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']



回答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')]



回答4:


grandparent = element.find_element_by_xpath('../..')


来源:https://stackoverflow.com/questions/21578785/get-grandparent-using-xpath-in-selenium-webdriver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!