Search code examples
javaseleniumselectselenium-webdriversiblings

Selenium: Select indirect sibling element


I have the following HTML structure:

<div class="UFICommentContentBlock">
    <div class="UFICommentContent">
    <span>
    <span>
        <span data-ft="{"tn":"K"}">
            <span class="UFICommentBody">
                <span>My comment text</span>
            </span>
        </span>
    </span>
    <div class="UFITranslatedText"></div>
    <span></span>
</div>
<div class="fsm fwn fcg UFICommentActions">
    <a class="UFILikeLink" data-ft="{"tn":">"}" data-testid="ufi_comment_like_link" href="#" role="button" title="Like this comment">Like</a>
    <span role="presentation" aria-hidden="true"> · </span>
    <a class="UFIReplyLink" href="#" role="button">Reply</a>
    <span role="presentation" aria-hidden="true"> · </span>
    <span>
</div>
<a class="UFICommentCloseButton _5upq _5upr _5upp _42ft" data-testid="ufi_comment_close_button" data-hover="tooltip" data-tooltip-alignh="center" data-tooltip-content="Edit or delete this" href="#" id="js_c">   </a>
</div>  

This is Facebook comment area. I have several comments below the post, each is of the same structure. I can find the required comment by

xpath("//div[@class='UFICommentContentBlock']//span[@class='UFICommentBody']//span[text()='My comment text']")  

I need to reach the Edit comment button of this comment who is also child of UFICommentContentBlock but not a direct sibling of the element containing the comment text so

xpath("//div[@class='UFICommentContentBlock']//span[@class='UFICommentBody']//span[text()='.']/following-sibling::div[@class='fsm fwn fcg UFICommentActions']/a[@class='UFICommentCloseButton _5upq _5upr _5upp _42ft']")  

doesn't work.
Need your assistance to select it


Solution

  • Use this:-

    //span[text()='My comment text']/ancestor::div[@class='UFICommentContentBlock']//a[contains(@class,'UFICommentCloseButton')]
    

    OR

    //span[text()=.]/ancestor::div[@class='UFICommentContentBlock']//a[contains(@class,'UFICommentCloseButton')]
    

    ID is also mentioned for a tag. So you can use id as well:-

    //span[text()=.]/ancestor::div[@class='UFICommentContentBlock']//a[@id='js_c']
    

    OR

    //a[@id='js_c']