![](/img/trans.png)
[英]org.openqa.selenium.NoSuchElementException WebDriver in Java?
[英]org.openqa.selenium.NoSuchElementException when navigating to child div Selenium Java
当前页面是https://www.nintendo.co.uk/Games/Games-347085.html
我已经使用 driver.findElement 为 div.row-page-container 运行了 Selenium 测试,它工作正常
但是当我尝试通过进一步进入页面信息下面的红线来获取价格值时,我找不到如何访问 class,它会记录:org.openqa.selenium.NoSuchElementException:没有这样的元素
如何获得价格价值,同时尽可能避免 XPath?
不知道为什么你不想拥有 XPath。
但是,如果您正在寻找基于游戏名称的 XPath,那可以得到它的价格。 您可以使用下面的 XPath
//p[text()='Animal Crossing: New Horizons']//following-sibling::p[@class='price-small']//span[@data-price]
或下面的 CSS 也应该足够了
a[href*='Animal-Crossing-New-Horizons'] > p.price-small > span:nth-child(2)
它基于href Animal-Crossing-New-Horizons
首先使用正确的 xpath 是去除 NoSuchElementException 的重要步骤。用于识别元素的 xpath 是
//p[text()='Animal Crossing: New Horizons']//following-sibling::p[@class='price-small']//span[@data-price]
即使这不能识别,网页也可能存在一些时间问题,即页面仍在呈现,并且您已经完成了元素搜索并且没有获得元素异常。
您可以使用FluentWait来克服这个问题。
假设您有一个元素,有时只需 1 秒即可出现,有时需要几分钟才能出现。 在这种情况下,最好使用FluentWait定义显式等待,因为这将一次又一次地尝试查找元素,直到找到它或直到最终计时器用完。
可以定义FluentWait的实例来配置等待条件的最长时间以及必须检查条件的频率。用户还可以配置等待以在等待元素时忽略特定类型的异常,比如页面上的 NoSuchElementExceptions。
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS);
.pollingEvery(5, SECONDS) ;
.ignoring(NoSuchElementException.class);
添加显式等待也可以解决问题:
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
. . .
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("element_xpath"))); element.click();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.