Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading