为什么我可以用 Xpath 找到第一个元素,但找不到第二个元素?

问题描述 投票:0回答:1

我正在尝试在 Selenium Webdriver 中构建一个测试来检查具有相同类名的 2 个 div 的值。

例如,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>

我一直在尝试使用 Selenium 的 Xpath 定位器,但似乎无法找到第二个 div。

例如,以下有效:

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

但这不起作用:

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

我收到错误

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

我不知道为什么在找到第一个元素时效果很好,但在找到第二个元素时却不起作用。

有人知道为什么吗?

javascript selenium-webdriver xpath
1个回答
0
投票

我宁愿使用

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

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

原因是因为 XPath 表达式

//div[@class='price'][2]
试图选择整个 HTML 文档中类名为“price”的第二个 div 元素,而不是特定上下文中类名为“price”的第二个 div 元素。

© www.soinside.com 2019 - 2024. All rights reserved.