有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Chrome浏览器处理“StaleElementReferenceException”

我正在测试新构建的框架,在使用Chrome浏览器时经常遇到org.openqa.selenium.StaleElementReferenceException。框架设计会有问题吗? 在其他浏览器中运行测试时没有问题。我尝试了多种类型的自定义等待,捕捉StaleElementReferenceException,然后循环查找元素,但没有成功

有没有人遇到过类似的问题并找到了解决方案

Chrome版本:38.0.2125.111
硒版本:2.43.1

public WebElement waitTill(By by){
    WebElement ele = null;
    for(int i=0; i<15; i++){
        try {
            ele = driver.findElement(by);
            if(ele==null)
                Thread.sleep(2000); //in last attempt used thread...we wont use this in actual practice
                else
                    break;
        } catch (NoSuchElementException | InterruptedException e) {
            System.out.println(e.getMessage());
        }
    }
    return ele;
}

public WebElement getElement(String loc) {
    String locator = initUtils.ORProp.getProperty(loc);
    WebElement element = null;
    try{
        By by = getBy(locator);
        element = waitTill(by);
    }catch(NoSuchElementException e){
        System.out.println(e.getMessage());
    }catch(StaleElementReferenceException e){
        By by = getBy(locator);
        element = waitTill(by);
    }
    return element;
}

共 (2) 个答案

  1. # 1 楼答案

    这种错误是由于在检查元素的时间间隔内网页发生更改而导致的

    我恐怕要说,这个例外主要是由糟糕的测试造成的。有几件事需要检查:

    • 确保你在进入页面时给了页面加载的时间 在你开始与它互动之前,即使你认为它 加载完毕,它可能仍在等待 背景,当它到达时,页面会发生变化

    • 确保如果与任何更改页面的元素进行交互 确保再次等待页面更改和任何html请求 处理

    这两件事可能是大多数问题的原因,我建议使用使用使用jQuery ajax start and stop的ajax,以确保在修改页面之前加载页面。你需要记住的是,selenium比用户与页面交互的速度快得多,你需要通过增加检查来处理这个问题

    我还建议在尝试与某个元素交互之前,检查该元素是否在页面上,以及该元素是否可见

    在更糟糕的情况下,senario可以使用try-and-catch块来检查元素,但如果确保页面没有更改,则不应出现异常。由于浏览器速度和webdriver速度的不同,浏览器之间确实存在差异

    我使用的一些代码是:

    var finished = false;
    
    function ready() {
      if (finished == true) {
        $( "#main" ).addClass("ready");
      }
    }
    
    $( document ).ajaxStart(function() {
      $( "#main" ).removeClass("ready");
      finished = false;
    });
    
    $( document ).ajaxStop(function() {
      finished = true;
      window.setTimeout(ready,500);
    });'
    

    这将检查页面是否已完全加载,并且没有任何请求处于挂起状态,我只需在浏览器打开后执行此操作,然后我就可以检查该类是否存在,以及是否已准备就绪。每当页面发生变化时,我也会进行同样的检查

  2. # 2 楼答案

    在编程方面,我可能会使用带有ExpectedConditions的显式等待,而不是线程。睡眠():

        public WebElement element2Click (By by){
          WebElement myClickableElement = (new WebDriverWait(driver, 10))
          .until(ExpectedConditions.elementToBeClickable(by));
    
          return myClickableElement;
    }
    

    但是,如果这不能解决问题,并且您的自动测试程序在其他浏览器中相当稳定,则可能是您正在测试的网页或webapp不支持Chrome,并且您可能会看到StaleElementReferenceException错误,因为HTTP消息没有正确通信。在这种情况下,请查看浏览器上的HTTP流量