My question is simple- Using Selenium, how do you keep on clicking links when each hyper link opens up in a new page or new window or opens in the same web page.
For example I have following links on a webpage: Log in Sign up Forgot Password? Signup with us follow this link Home Terms Privacy Policy
Here is the small snippet of code that I have written to click these mentioned links on webpage:
List<WebElement> elements = driver.findElements(By.tagName("a"));
//clicking all links
for (WebElement el : elements){
System.out.println("Link getting clicked" + el.getText());
el.click();
driver.navigate().back();
}
As you can see I am trying to get links and trying to click them one by one. However, I am getting an error after the first click itself. Console says: "org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM".
I am petty sure I know the cause as the links are getting opened on the same webpage, but I am doing a back navigation, which is not helping me at all.
Any thoughts / suggestions?
This could be due to program execution advancing to the call to "driver.navigate().back();" before the page has loaded.
Try introducing an implicit wait , which tells the "WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available"
eg When you create your web driver try:
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
You have to refind the element whenever a page is reloaded before you can interact with it, for your code, please try modify them to this:
driver.manage().timeouts().implicitlyWait(3000, TimeUnit.MILLISECONDS);
List<WebElement> elements = driver.findElements(By.tagName("a"));
//clicking all links
for (int i=0; i<elements.size(); i++){
WebElement el = driver.findElements(By.tagName("a")).get(i);
System.out.println("Link getting clicked" + el.getText());
el.click();
driver.navigate().back();
}
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.