Reputation: 100
Today I've met this problem: I have some html code:
<div class="Main">
<div>
<div class="display">First:</div>
<div class="price">$0.01</div>
</div>
<div>
<div class="display">Second:</div>
<div class="price">$0.02</div>
</div>
<div>
<div class="display">Third:</div>
<div class="price">$0.03</div>
</div>
</div>
I want to find second element, for example. What should i do? I'm using Java and Selenium and this way isn't working:
chromeDriver.findElement(By.className("Main"))
.findElement(By.xpath(".//*[starts-with(@class, 'price')][2]")).getText()
I know about findElements-method, but i want through xpath.
Upvotes: 1
Views: 520
Reputation: 29
Using the [1] or [2] in the xpath is NOT a good approach...because when the structure of the page changes your locator will not point it to the same Web element.
Better solution of the problem would be using the text between the tags. If the text between the tag is the unique one u can directly use the text content of them in your xpath and have an access to the second element.
xpath = "//div[conatins(text(),'$0.02')]" ;
This would help you.
Upvotes: 1
Reputation: 618
Looking at your XPath expression there are a couple of problems:
<div>
that contains the <div class="display"></div>
and <div class="price"></div>
elements.()
if you want to retrieve an element based on its index.findElement
twice.Here is the expression I would use. Notice that it:
<div class="Main">
element<div>
text()
using XPath ()
so we can use the index accessor(//*[@class='Main']/*/*[starts-with(@class, 'price')])[2]/text()
Upvotes: 1