Search code examples
javascriptselenium-webdriverxpath

Why can I find the first, but not the 2nd element with Xpath?


I am trying to build a test in Selenium Webdriver to check the values of 2 divs that have the same class name.

Eg, HTML:

<div class="prod-card">
  <div class="prices">
    <div class="price-wrap">
      From: 
      <div class="price">$9.99</div>
    </div>
    <div class="price-wrap">
      To: 
      <div class="price">$19.99</div>
    </div>
  </div>
</div>

I've been trying to use Selenium's Xpath locator, but cannot seem to locate the 2nd div.

Eg, the below works:

let lowerPrice = await driver.findElement(By.xpath("//div[@class='price'][1]")).getText();
lowerPrice = lowerPrice.trim();
assert.equal(lowerPrice, expectations[i].lowerPrice);

But this does not work:

let higherPrice = await driver.findElement(By.xpath("//div[@class='price'][2]")).getText();
higherPrice = higherPrice.trim();
assert.equal(higherPrice, expectations[i].higherPrice);

I get the error NoSuchElementError: Unable to locate element: //div[@class='price'][2]

I don't know why this works fine when finding the first element, but not the 2nd.

Would anyone know why?


Solution

  • I will rather use

    //div[@class='price-wrap'][1]/div[@class='price']
    

    and

    //div[@class='price-wrap'][2]/div[@class='price']
    

    The reason is because the XPath expression //div[@class='price'][2] is attempting to select the second div element with the class name 'price' in the entire HTML document, rather than the second div element with the class name 'price' within a specific context.