找不到元素 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.tw/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