how to get a sub parent web element component betw

2019-09-06 10:50发布

问题:

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