Chusya
Chusya

Reputation: 100

Find an element using xpath

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

Answers (2)

K Shashank
K Shashank

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

Ivan Kahl
Ivan Kahl

Reputation: 618

Looking at your XPath expression there are a couple of problems:

  • You need to accommodate for the container <div> that contains the <div class="display"></div> and <div class="price"></div> elements.
  • You need to wrap your selector in () if you want to retrieve an element based on its index.
  • You can use a single XPath expression instead of calling findElement twice.

Here is the expression I would use. Notice that it:

  • Looks for the <div class="Main"> element
  • Accommodates the container <div>
  • Retrieves the text() using XPath
  • Wraps the selector in () so we can use the index accessor

(//*[@class='Main']/*/*[starts-with(@class, 'price')])[2]/text()

Upvotes: 1

Related Questions