简体   繁体   中英

Not able to click all links on a web page using Java and 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);
        }
    }
}  

When I run this code I get following error:-

org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

I tried with implicit wait as well but getting same issue.

Each time the DOM is changed or refreshed, like in going to different page, the driver loses the elements it previously located. You need to relocate the list each iteration

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM