【问题标题】:"Unable to locate element" exception with WebDriverWebDriver 出现“无法定位元素”异常
【发布时间】:2012-08-22 11:21:23
【问题描述】:

运行以下代码时出现“无法定位元素”异常。我的预期输出是First Page of GoogleResults

public static void main(String[] args) {
    WebDriver driver;
    driver = new FirefoxDriver();
    driver.get("http://www.google.com");
    driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);

    WebElement oSearchField = driver.findElement(By.name("q"));
    oSearchField.sendKeys("Selenium");

    WebElement oButton = driver.findElement(By.name("btnG"));
    oButton.click();

    //String oNext = "//td[@class='b navend']/a[@id='pnnext']";
    WebElement oPrevious;
    oPrevious = driver.findElement(By.xpath("//td[@class='b navend']/a[@id='pnprev']"));

    if (!oPrevious.isDisplayed()){
        System.out.println("First Page of GoogleResults");
    }
}

如果我运行上面的代码,我会得到“无法定位元素异常”。我知道Previous Button Element不在Google搜索结果页面的第一页,但我想抑制异常并获取下一步if条件的输出。

【问题讨论】:

  • 在 retaging 之后,即使我将 java 作为最后一个选项,为什么它会作为第一个出现。页面标题因此而混乱。可能会产生误导。有什么想法吗?

标签: java selenium webdriver selenium-webdriver


【解决方案1】:

逻辑错误-

oPrevious = driver.findElement(By.xpath("//td[@class='b navend']/a[@id='pnprev']"));

如果 WebDriver 无法定位元素,将失败或报错。

尝试使用类似 -

public boolean isElementPresent(By by) {
    try {
        driver.findElement(by);
        return true;
    } catch (NoSuchElementException e) {
        return false;
    }
}

您可以将 xpath 传递给函数,如

boolean x = isElementPresent(By.xpath("//td[@class='b navend']/a[@id='pnprev']"));
if (!x){
    System.out.println("First Page of GoogleResults");
}

【讨论】:

  • 好东西,记住在导入时要导入 org.openqa.selenium.NoSuchElementException 而不是 java.util.NoSuchElementException(就像我的 IDE 最初所做的那样)。
猜你喜欢
  • 2014-01-26
  • 2016-04-15
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 2016-12-10
  • 2018-09-30
  • 2012-04-27
  • 1970-01-01
相关资源
最近更新 更多