[英]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
org.openqa.selenium.StaleElementReferenceException:陈旧元素引用:元素未附加到页面文档
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. 每次更改或刷新DOM(例如转到不同的页面)时,
driver
丢失其先前定位的元素。 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.