Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath selecting sibling from parent

Tags:

xpath

I'm new to xpath, so please forgive me. I have multiple autocompletes that use tokens. I'm trying to select child <p> based on text Some Text 1 from parent div.title=title and get the sibling span.remove-token.

Example

<div title="title">
    <ul class="token-list">
        <li class="input-token"
            <p>Some Text 1</p>
            <span class="remove-token">x</span>
        </li>
        <li class="input-token"
            <p>Some Text 2</p>
            <span class="remove-token">x</span>
        </li>
    </ul>
</div>

What I've attempted

String path = "//div[contains(@title, 'title')]/p[text()="Some Text 1"]/following-sibling::span]";
like image 354
Code Junkie Avatar asked Dec 03 '12 20:12

Code Junkie


People also ask

How do you find the XPath of parent siblings?

A Sibling in Selenium Webdriver is a function used to fetch a web element which is a sibling to the parent element. If the parent element is known then the web element can be easily found or located that can use the sibling attribute of the Xpath expression in selenium webdriver.

Where do we use following siblings in XPath?

We can use the concept of following-sibling in xpath for identifying elements in Selenium. It identifies the siblings of the context node. The siblings should be located at the equal level of the existing node and should have the same parent.

How can I get next sibling in XPath?

To traverse to the next sibling, we have to use the following-sibling concept in xpath. This will allow us to traverse to the next sibling from the present sibling of the same parent. Let us try to move from the first child<h1> of parent <div> to the second <h2> as in the above image.


2 Answers

Use:

//div[@title = 'title']//li/p[. = 'Some Text 1']/following-sibling::span[1]
like image 111
Dimitre Novatchev Avatar answered Sep 18 '22 09:09

Dimitre Novatchev


Try

//div[contains(@title,'title')]//p[text()="Some Text 1"]/following-sibling::span

There were two tiny mistakes:

  1. there was an unnecessary ] at the end of the expression
  2. the p element is not a direct child of the div, so you must search all descendants
like image 40
Petr Janeček Avatar answered Sep 20 '22 09:09

Petr Janeček