Java 尝试单击元素时出现StaleElementReferenceException

Java 尝试单击元素时出现StaleElementReferenceException,java,selenium,selenium-webdriver,Java,Selenium,Selenium Webdriver,我正在使用Java实现一个Selenium测试。但是,由于StaleElementReferenceException,我的测试失败 driver.get(URL); List<WebElement> Anchors = driver.findElements(By.xpath("//div[not(contains(@style,'display:none'))]/a")); //same URL again driver.get(URL); Anchors.get(0).cl

我正在使用
Java
实现一个
Selenium
测试。但是,由于
StaleElementReferenceException
,我的测试失败

driver.get(URL);
List<WebElement> Anchors = driver.findElements(By.xpath("//div[not(contains(@style,'display:none'))]/a"));

//same URL again

driver.get(URL);
Anchors.get(0).click();
driver.get(URL);
列表锚=driver.findelelements(By.xpath(“//div[not(contains(@style,'display:none')))]/a”);
//还是同一个URL
获取(URL);
获取(0)。单击();

当我尝试单击锚列表中的任何元素时,我会得到一个错误。

每当DOM更改或刷新时,即使您仍在同一页面中,驱动程序也会“丢失”它以前定位的
WebElements
,您会得到
StaleElementReferenceException
。如果你真的需要使用
driver.get(URL)您何时尝试单击它?在我重新打开相同的URL之后,您是指在第二个
驱动程序.get(URL)之后?是的,例如,如果我使用Anchors.get(0),请在第二个driver.get(URL)语句后单击();一旦刷新(重新打开)页面,您定义的元素就会过时。您需要在每个
驱动程序之后重新定义链接列表。获取(URL)
。但是,我建议您只获取每个锚元素的引用列表(
getAttribute('href')
),并在其中循环