how to get a sub parent web element component between many div in selenium xpath?

随声附和 提交于 2020-01-07 05:42:13

问题


I want to get the sub parent element <div class="post"/> given the text of a post in this case given the text "post2" that is the second div in the code there are many posts in a page.

I tried to use an xpath like this that I did thinking that is possible find between in the sub-parents web elements: "//div[@id='content']//span[contains(text(), 'post2')]/.//*[@class='post']"

<div id="content">
    <div class="post">
        <div class="right">
            <div class="content">
                <div class="post-content">
                    <span>
                        post1
                    </span>
                </div>
            </div>
        </div>  
    </div>
    <div class="post">
        <div class="right">
            <div class="content">
                <div class="post-content">
                    <span>
                        post2
                    </span>
                </div>
            </div>
        </div>  
    </div>
</div>

exists any other solution for that or maybe the xpath is wrong?


回答1:


a solution that exists is using the "ancestor" keyword:

//div[@id='content']//span[contains(text(), 'post2')]/ancestor::div[@class='post']



回答2:


Alternatively, you can put the 'span checking' as predicate for the <div class="post"> :

//div[@id='content']/div[@class='post'][.//span[contains(text(),'post2')]]

This way you don't need to go back up the tree to the ancestor <div class="post"> after going straight to the span



来源:https://stackoverflow.com/questions/33947216/how-to-get-a-sub-parent-web-element-component-between-many-div-in-selenium-xpath

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