使用下一个按钮浏览Google搜索页面并通过WebDriver打印链接标题

时间:2016-03-28 09:12:19

标签: java selenium selenium-webdriver webdriver

我正在尝试逐页打印搜索结果的所有标题。

搜索谷歌然后打印首页结果的标题是成功的。但是,当我尝试单击下一步按钮然后打印第二页结果的标题时,我收到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 个答案:

答案 0 :(得分:0)

@praveen kumar - 您可以在到达下一页时更新代码。确定要打印的文本的xpath,并在下面的代码中更新xpath / class id / link id,它将适合您:

@Test(priority=2)
        public void printPageHeader() throws InterruptedException{

            java.util.List<WebElement> allText = driver.findElements(By.xpath("//*[@id='app']/div/header/nav[1]/div/div/span/span"));
            for ( WebElement element: allText) { 
                System.out.println(element.getText());
        }  
        }

答案 1 :(得分:-1)

@ Praveen Kumar首先请理解什么是陈旧元素异常。在两种情况之一中引发陈旧元素引用异常,

1.The element has been deleted entirely.(more common)
2.The element is no longer attached to the DOM.

欲了解更多信息,请访问selenium官方网站http://docs.seleniumhq.org/exceptions/stale_element_reference.jsp

现在解决你的问题

public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver", "D:\\eclipseProject\\StackOverFlow\\chromedriver_win32 (1)\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.google.co.in/?gfe_rd=cr&ei=OhT5VrLwE-iK8QfV74WwCA");

        // performing google search
        driver.findElement(By.name("q")).sendKeys("Selenium Interview Questions");
        driver.findElement(By.name("btnG")).click();

        // printing all sites name 

        List<WebElement> allsites = driver.findElements(By.xpath("//*[@id='rso']/div/div/div[@class='rc']/h3/a"));
        for(int i =0;i<allsites.size();i++){
            System.out.println("All Sites Name is : " + allsites.get(i).getText());
            // now clicking link to go to the next page 
            allsites.get(i).click();

            // getting title of the opened URL
            System.out.println("Title of the Next Page is : "+ driver.getTitle());

            // navigating back to the previous page 
            driver.navigate().back();

            // now when you will try to click the next link in the line you will face 
            // Stale Element Exception as element is not attached to the page document
            // so re-attached it we have to redefine it.
            allsites = driver.findElements(By.xpath("//*[@id='rso']/div/div/div[@class='rc']/h3/a"));

            // now it will work like a charm. Hope this solves the issue
        }

    }

希望这能解决你的问题。