Find an element using xpath

Chusya :

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.

Ivan Kahl :

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()

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=420870&siteId=1