在运行下面的代码时,我得到了一个“找不到元素”的异常。我的预期输出是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");
}
}如果我运行上面的代码,我会得到"Unable to Locate Element Exception“。我知道前一个按钮元素不在谷歌搜索结果页面的第一页,但我想抑制异常,并获得下一步if条件的输出。
发布于 2012-08-22 19:42:45
逻辑错误-
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");
}https://stackoverflow.com/questions/12071977
复制相似问题