我无法理解如何在找不到元素时处理硒。我目前的代码是:
READ COMMITTED
但是当它找不到元素时我会收到这个错误:
WebDriver driver = new PhantomJSDriver();
for (FeedItem item : items){
String url = item.getLink();
System.out.println("Retrieving: " + item.getTitle() + " from: " + url);
driver.get(url);
System.out.println("Got URL");
try{
WebElement title = driver.findElement(By.className("story-body__h1")); // NoSuchElementException is thrown here
WebElement body = driver.findElement(By.className("story-body__inner"));
List<WebElement> story = body.findElements(By.tagName("p"));
for (WebElement part : story){
System.out.println(part.getText());
}
System.out.println();
} catch (NoSuchElementException | ScreenshotException e) {
System.err.println("Unable to find element");
}
}
driver.close();
}
并且线程被阻止。 (我不能在eclipse中单击停止,我必须使用terminate并从调试器视图中删除以停止执行)
我该如何处理此错误?
编辑:如果我只是捕获所有异常,那么它会按预期继续,那么我应该捕获什么异常?
答案 0 :(得分:2)
检查您是否导入了正确的课程。它应该是
import org.openqa.selenium.NoSuchElementException