【问题标题】:Getting Error "Stale element reference: element is not attached to the page document" in selenium -Java在 selenium -Java 中出现错误“过时的元素引用:元素未附加到页面文档”
【发布时间】:2019-10-09 09:10:21
【问题描述】:

我必须通过 foreach 循环迭代 List 并且需要单击项目。列表的第一项被点击,但从第二项开始我得到了

org.openqa.selenium.StaleElementReferenceException:过时的元素 参考:元素未附加到页面文档

public void checkFlightAvailabilityToSelectOutBound() throws InterruptedException {

    boolean enabledFound=BookDateFlight();
    System.out.println("checkFlightAvailabilityToSelectOutBound  "+enabledFound);

    if(enabledFound==false)
    {
        List<WebElement> nextAvailableDateList = driver
                .findElements(By.xpath("somexpath"));
        System.out.println("date list lenth "+nextAvailableDateList.size());
        **for (WebElement nxtAvlDate : nextAvailableDateList) 
        {
            try {
            System.out.println("------"+nxtAvlDate);
            System.out.println("Trying to click on the nxt avl date "+nxtAvlDate.getAttribute("id"));
            //wait.until(ExpectedConditions.elementToBeClickable(nxtAvlDate));
            //driver.navigate().refresh();
            Thread.sleep(3000);
            nxtAvlDate.click();
            Thread.sleep(5000);**
            //wait.until(ExpectedConditions.visibilityOfAllElements(flightInfoOutBoundTravelClassBtnList));
            }catch(Exception e) {
                e.printStackTrace();
                System.out.println("message catch"+e.getMessage());

            }

            enabledFound=BookDateFlight();
            System.out.println("After clicking nxt avil date "+enabledFound);
            if(enabledFound==true)
            {
                break;
            }
        }
        if(enabledFound==false)
        {
            System.out.println("inside next 7 day");
            driver.findElement(By.xpath("//p[@class='next']")).click();
            System.out.println("inside next 7 day clicked");
            Thread.sleep(10000);
            checkFlightAvailabilityToSelectOutBound();

            }

    }

}

【问题讨论】:

标签: selenium-webdriver


【解决方案1】:

在 staleelementexception 的情况下,问题通常是由于请求对已更新或新元素的引用(即使它可能具有相同的 id),因此我们对它的引用无效。可以通过要求项目的干净引用或在工作流程中添加等待来解决

你可以试试这样的:

WebDriverWait wait = (WebDriverWait)new WebDriverWait(driver,timeout)
                  .ignoring(StaleElementReferenceException.class); 
  wait.until(new ExpectedCondition<Boolean>(){ 
    @Override 
    public Boolean apply(WebDriver webDriver) { 
      WebElement element = webDriver.findElement(by); 
      return element != null && element.isDisplayed(); 
    } 
  }); 

根据您的代码调整它

【讨论】:

  • 你能给我一些例子(代码sn-p)如何处理这个。
【解决方案2】:

它通常在 dom 刷新时发生。在单击之前尝试以下显式等待

wait.until(ExpectedConditions.stalenessOf(nxtAvlDate));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 2019-04-23
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2015-02-07
    相关资源
    最近更新 更多