Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath to select following-sibling

Tags:

selenium

xpath

This is the code that I currently have:

<div>
<ul class="nav nav-pills nav-stacked">
<li>
<li>
<li>
<li>
<li>
<section>
<span name="merchant">ABZ</span>
</section>
<section>
<span class="glyphicon glyphicon-pencil" name="edit"></span>
<span class="glyphicon glyphicon-remove" name="delete"></span>
</section>
</li>
<li>
<li>
<li>
<li>
</ul>
<div class="add-item bottom" name="new-merchant">
</div>

I have tried the following:

xpath=//span[contains(.,'ABZ')]/following-sibling::section/span[@name='edit']
xpath=//span[contains(.,'ABZ')]/following-sibling::span[1]

I am using selenium, and I want it to click on the edit button that is right after the ABZ span.

like image 519
user3525228 Avatar asked Apr 11 '14 20:04

user3525228


People also ask

How do you write XPath with following siblings?

Example #1 xpath("//a[contains(text()," + "'Second Window. ')]/parent::div//following-sibling::div[@class='cca']//a")); Here, the Firefox driver is invoked after the WebDriver API class 'Firefox Driver' is instantiated. The WebDriver object is then used to call and load the URL under test.

How does XPath select sibling elements?

Select all A sibling elements that precede the context node. > Select all A sibling elements that follow the context node. > Select all sibling elements that precede the context node. > Select the first preceding sibling element named A in reverse document order.

What is XPath siblings?

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.


2 Answers

Adding to the answer above, both the expressions below will work well.

//span[contains(text(), 'ABZ')]/following::section/span[@name='edit']

OR

//span[contains(text(), 'ABZ')]/../following-sibling::section/span[@name='edit']

Notably, the axis following will pick each node following the context node while the axis following-sibling will only pick the sibling nodes to the context node.

like image 117
Mohit Arora Avatar answered Oct 11 '22 18:10

Mohit Arora


This xpath worked for me in Chrome, using your html:

//span[contains(text(), 'ABZ')]/../following-sibling::section/span[@name='edit']

Edit

The .. means to go up a level. The .. takes the selector from span to section. Then the following-sibling finds the section after the parent section of your matching span.

Your original selector was matching span, then looking for a following-sibling to span.

like image 38
Richard Avatar answered Oct 11 '22 18:10

Richard