无法使用Java和Selenium Webdriver单击网页上的所有链接

时间:2017-03-05 09:48:51

标签: java selenium selenium-webdriver

package testPackage;

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.*;

public class AllLinkVerificationInAPage {
    WebDriver driver;
    @BeforeTest
    public void OpenApp()
    {
        System.setProperty("webdriver.chrome.driver", "E:/Selenium/Webdriver   /Softwares/chromedriver.exe");
        driver = new ChromeDriver();
        driver.navigate().to("http://ndtv.com/");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        WebElement popUp = driver.findElement(By.xpath("//*[@id='__cricketsubscribe']/div[2]/div[2]/a[1]"));
        popUp.click();      
    }

    @Test
    public void clickLinks() throws InterruptedException
    {
        //extract the list of WenElements and its count
        List<WebElement> linkElements =  driver.findElements(By.tagName("a"));
        int count = linkElements.size();
        System.out.println("Total number of links = " + count );

        //test each link
        for(WebElement currentElement : linkElements)
        {
            String link = currentElement.getText();
            System.out.println(link);
            if(link !="")
            {
                currentElement.click();
                System.out.println("Working Fine");

            }

            driver.navigate().back();
            Thread.sleep(3000);
        }
    }
}  

当我运行此代码时,我收到以下错误: -

  

org.openqa.selenium.StaleElementReferenceException:陈旧元素   reference:元素未附加到页面文档

我尝试了隐式等待,但遇到同样的问题。

1 个答案:

答案 0 :(得分:0)

每次更改或刷新DOM时,就像转到不同的页面一样,driver会丢失之前定位的元素。您需要在每次迭代时重新定位列表

int count = driver.findElements(By.tagName("a")).size();
for (int i = 0 ; i < count ; ++i) {
    List<WebElement> linkElements =  driver.findElements(By.tagName("a"));
    WebElement currentElement = linkElements.get(i);

    String link = currentElement.getText();
    System.out.println(link);
    if(link != "")
    {
        currentElement.click();
        System.out.println("Working Fine");
    }

    driver.navigate().back();
    Thread.sleep(3000);
}