找不到元素 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();
   }
}

输出

更新于: 07-4 月-2021

8K+ 浏览量

开启您的 事业

通过完成课程获得认证

开始学习
广告
© . All rights reserved.