找不到元素 xpath 错误 in selenium-java
在使用 Selenium webdriver 时,我们可能会遇到错误 - 找不到元素。这会导致 NoSuchElementException。当页面上没有与定位器值匹配的元素时,就会引发此类异常。

如果遇到错误,我们可以通过以下方式修复它 -
检查 xpath 表达式中是否存在任何语法错误。
向元素添加额外的预期等待条件。
使用替代 xpath 表达式。
例子
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class XpathError{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//launch URL
driver.get("https://tutorialspoint.com/index.htm");
WebElement m = driver.findElement(By.xpath("//*[text()='Library']"));
m.click();
//explicit wait condition - visibilityOfElementLocated
w.until(ExpectedConditions.visibilityOfElementLocated (By.linkText("Subscribe to Premium")));
System.out.println("Page title: " + driver.getTitle());
driver.quit();
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP