1

运行以下代码时出现“无法定位元素”异常。我的预期输出是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");
    }
}

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

4

1 回答 1

1

Logical mistake -

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

will fail or give error if WebDriver can't locate the element.

Try using something like -

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

You can pass the xpath to the function like

boolean x = isElementPresent(By.xpath("//td[@class='b navend']/a[@id='pnprev']"));
if (!x){
    System.out.println("First Page of GoogleResults");
}
于 2012-08-22T11:42:45.053 回答