为何在Selenium中用Xpath能定位第一个.price元素,却找不到第二个?
Selenium定位第二个.price元素失败的原因与解决方法
问题根源
你使用的XPath表达式//div[@class='price'][2]逻辑存在错误:
XPath中,[n]后缀是对当前节点的同级节点进行位置筛选。也就是说,这个表达式会寻找所有class='price'的div,且要求该元素是其父节点下的第二个div子元素。但你的两个.price元素分别位于不同的.price-wrap父节点中,每个父节点下只有一个.price子元素,因此不存在符合[2]条件的元素,自然抛出NoSuchElementError。
而//div[@class='price'][1]能生效,是因为每个父节点下的.price都是第一个(也是唯一一个)div子元素,所以表达式会返回文档中第一个匹配到的.price元素。
解决方法
方法1:修正XPath表达式
将整个匹配集合用括号包裹,再通过索引选取第二个元素,这样是对所有匹配到的.price元素进行位置筛选:
let higherPrice = await driver.findElement(By.xpath("(//div[@class='price'])[2]")).getText(); higherPrice = higherPrice.trim(); assert.equal(higherPrice, expectations[i].higherPrice);
方法2:获取元素列表后选取
先获取所有.price元素的数组,再通过数组索引选取第二个元素(注意JavaScript数组是0索引):
let priceElements = await driver.findElements(By.className("price")); let higherPrice = await priceElements[1].getText(); higherPrice = higherPrice.trim(); assert.equal(higherPrice, expectations[i].higherPrice);
方法3:结合上层节点精准定位
通过上层的.price-wrap节点定位,避免全局搜索的歧义:
let higherPrice = await driver.findElement(By.xpath("//div[@class='prod-card']//div[@class='price-wrap'][2]/div[@class='price']")).getText(); higherPrice = higherPrice.trim(); assert.equal(higherPrice, expectations[i].higherPrice);
内容的提问来源于stack exchange,提问作者MeltingDog
相关产品推荐
相关产品推荐

