我试图打印所有的搜索结果的标题页。
搜索google,然后打印第一页结果的标题是成功的。但是,当我试图单击“下一步”按钮,然后打印第二页结果的标题时,我得到了 StaleElementReferenceException: Element not found in the cache
错误。
如何在单击第一页上的“下一步”按钮后打印第二页标题。
我的代码:
public class goopick {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
searchGoogle(driver, "Selenium Interview Questions");
printSiteNames(getSiteNames(driver));
clickNextButton(driver);
printSiteNames(getSiteNames(driver));
}
private static List<WebElement> getSiteNames(WebDriver driver){
return driver.findElements(By.xpath("//*[@id='rso']/div/div/div[@class='rc']/h3/a"));
}
private static void searchGoogle(WebDriver driver, String searchString) {
driver.get("https://www.google.co.in/?gfe_rd=cr&ei=LSX1VvXDLKmumQW7irJw&gws_rd=ssl");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("lst-ib")).sendKeys(searchString);
driver.findElement(By.className("lsb")).click();
}
private static void printSiteNames(List<WebElement> sitenames) {
int i = 1;
System.out.println("----------------------------------xxxx----------------------------");
for (WebElement sitename : sitenames) {
String site = sitename.getText();
System.out.println(i + ") " + site);
i++;
}
System.out.println("----------------------------------xxxx----------------------------");
}
private static void clickNextButton(WebDriver driver) {
WebElement NextButton = driver.findElement(By.xpath("//a[@id='pnnext']/span[2]"));
NextButton.click();
System.out.println("Next Button Clicked");
driver.navigate().forward();
}
}
输出和错误:
Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
Command duration or timeout: 30.79 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
2条答案
按热度按时间cunj1qz11#
@praveen kumar-你可以在下一页更新你的代码。为要打印的文本标识xpath,并在下面的代码中更新xpath/类id/链接id,它将适用于您:
wqlqzqxt2#
@praveen kumar首先请理解什么是过时元素异常。在以下两种情况中的一种情况下会引发过时元素引用异常,
欲了解更多信息,请访问selenium官方网站
http://docs.seleniumhq.org/exceptions/stale_element_reference.jsp
现在解决你的问题希望这能解决你的问题。