41

我在 Selenium 2 Web 驱动程序测试中有以下代码,它在我调试时有效,但在我在构建中运行它时大部分时间都失败了。我知道这一定与页面未刷新的方式有关,但不知道如何解决它,因此任何关于我做错了什么的指针都值得赞赏。我使用 JSF primefaces 作为我的 Web 应用程序框架。当我单击添加新链接时,会出现一个弹出对话框,其中包含一个输入框,我可以在其中输入日期,然后单击保存。在让输入元素输入文本时,我得到了一个陈旧的元素引用异常。

提前致谢

import static org.junit.Assert.assertEquals;

 import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;


public class EnterActiveSubmissionIntegrationTest {
Map<String, Map<String, String>> tableData = new HashMap<String, Map<String, String>>();

@Test
public void testEnterActiveSubmission() throws Exception {
    // Create a new instance of the Firefox driver
    // Notice that the remainder of the code relies on the interface, 
    // not the implementation.
    System.setProperty("webdriver.chrome.driver", "C:/apps/chromedriver.exe");
    WebDriver driver = new ChromeDriver();

    // And now use this to visit Google
    driver.get("http://localhost:8080/strfingerprinting");
    // Alternatively the same thing can be done like this
    // driver.navigate().to("http://www.google.com");

    // Find the text input element by its name
    WebElement element = driver.findElement(By.linkText("Manage Submissions"));
    element.click();
    parseTableData(driver, "form:submissionDataTable_data", 1);
    assertEquals(tableData.get("form:submissionDataTable_data").get("12"), "Archived");

    WebElement newElement = driver.findElement(By.linkText("Add new"));
    newElement.click();

    WebDriverWait wait = new WebDriverWait(driver,10);
    wait.until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver driver) {
            WebElement button = driver.findElement(By
                    .name("createForm:dateInput_input"));

            if (button.isDisplayed())
                return true;
            else
                return false;

        }
    });

    WebElement textElement = driver.findElement(By.name("createForm:dateInput_input"));
    textElement.sendKeys("24/04/2013");
    WebElement saveElement = driver.findElement(By.name("createForm:saveButton"));
    saveElement.click();

    driver.navigate().refresh();

    parseTableData(driver, "form:submissionDataTable_data", 2);

    //Close the browser
    driver.quit();
}



private void parseTableData(WebDriver driver, String id, int expectedRows) {
    // Check the title of the page or expected element on page
    WebElement subTableElement = driver.findElement(By.id(id));
    List<WebElement> tr_collection=subTableElement.findElements(By.xpath("id('"+ id + "')/tr"));

    assertEquals("incorrect number of rows returned", expectedRows, tr_collection.size());
    int row_num,col_num;
    row_num=1;

    if(tableData.get(id) == null) {
        tableData.put(id, new HashMap<String, String>());
    }
    Map<String, String> subTable = tableData.get(id);
    for(WebElement trElement : tr_collection)
    {
        List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
        col_num=1;
        for(WebElement tdElement : td_collection)
        {
            subTable.put(row_num + "" + col_num, tdElement.getText());
            col_num++;
        }
        row_num++;
    }
}
}

当我运行它时,我得到以下异常,但它可能发生在

WebElement textElement = driver.findElement(By.name("createForm:dateInput_input")); 

或者

if (button.isDisplayed())

异常跟踪

org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
(Session info: chrome=26.0.1410.64)
  (Driver info: chromedriver=0.8,platform=Windows NT 6.0 SP2 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 56 milliseconds
For documentation on this error, please visit:        http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.32.0', revision: '6c40c187d01409a5dc3b7f8251859150c8af0bcb', time: '2013-04-09 10:39:28'
System info: os.name: 'Windows Vista', os.arch: 'x86', os.version: '6.0', java.version: '1.6.0_10'
Session ID: 784c53b99ad83c44d089fd04e9a42904
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true,   browserName=chrome, rotatable=false, driverVersion=0.8, locationContextEnabled=true,  version=26.0.1410.64, cssSelectorsEnabled=true, databaseEnabled=true, handlesAlerts=true,  browserConnectionEnabled=false, nativeEvents=true, webStorageEnabled=true,   applicationCacheEnabled=false, takesScreenshot=true}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:187)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
at org.openqa.selenium.remote.RemoteWebElement.isDisplayed(RemoteWebElement.java:320)
at com.integration.web.EnterActiveSubmissionIntegrationTest$1.apply(EnterActiveSubmissionIntegrationTest.java:58)
at com.integration.web.EnterActiveSubmissionIntegrationTest$1.apply(EnterActiveSubmissionIntegrationTest.java:1)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:208)
at com.integration.web.EnterActiveSubmissionIntegrationTest.testEnterActiveSubmission(EnterActiveSubmissionIntegrationTest.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
4

22 回答 22

66

首先让我们弄清楚 WebElement 是什么。

WebElement 是对 DOM 中元素的引用。

当您正在交互的元素被销毁然后重新创建时,将引发 StaleElementException。如今,大多数复杂的网页都会在用户与其交互时动态移动,这需要销毁和重新创建 DOM 中的元素。

发生这种情况时,您之前拥有的对 DOM 中元素的引用变得陈旧,并且您不再能够使用此引用与 DOM 中的元素进行交互。发生这种情况时,您将需要刷新您的参考,或者在现实世界中再次找到该元素。

于 2013-04-26T20:31:11.607 回答
24

这不是问题。如果将 .findElement 调用包装在 try-catch 块中并捕获 StaleElementReferenceException ,则可以根据需要循环并重试多次,直到成功。

下面是我写的一些例子

Selenide项目的另一个例子:

public static final Condition hidden = new Condition("hidden", true) {
    @Override
    public boolean apply(WebElement element) {
      try {
        return !element.isDisplayed();
      } catch (StaleElementReferenceException elementHasDisappeared) {
        return true;
      }
    }
  };
于 2013-06-04T15:54:55.293 回答
20

发生在我身上的是 webdriver 会找到对 DOM 元素的引用,然后在获得该引用后的某个时间点,javascript 会删除该元素并重新添加它(因为页面基本上正在重绘)。

尝试这个。找出导致 dom 元素从 DOM 中删除的操作。在我的例子中,它是一个异步 ajax 调用,当 ajax 调用完成时,该元素正在从 DOM 中删除。在该操作之后,等待元素过时:

... do a thing, possibly async, that should remove the element from the DOM ...
wait.until(ExpectedConditions.stalenessOf(theElement));

此时,您可以确定该元素现在已过时。所以,下次你引用该元素时,再次等待,这一次等待它被重新添加到 DOM 中:

wait.until(ExpectedConditions.presenceOfElementLocated(By.id("whatever")))
于 2014-03-19T10:18:08.683 回答
12

陈旧元素的两个原因

  1. 在 WebDriver 中作为 WebElement 引用的网页上找到的元素,然后 DOM 发生变化(可能是由于 JavaScript 函数),WebElement 变得陈旧。

  2. 该元素已被完全删除。

当您尝试与过时的 WebElement [上述任何情况] 进行交互时,将引发 StaleElementException。

如何避免/解决陈旧异常?

  1. 将定位器存储到元素而不是引用
driver = webdriver.Firefox();
driver.get("http://www.github.com");
search_input = lambda: driver.find_element_by_name('q');
search_input().send_keys('hello world\n'); 
time.sleep(5);


search_input().send_keys('hello frank\n') // no stale element exception
  1. 利用所使用的 JS 库中的钩子
   # Using Jquery queue to get animation queue length.
    animationQueueIs = """
    return $.queue( $("#%s")[0], "fx").length;
    """ % element_id
    wait_until(lambda: self.driver.execute_script(animationQueueIs)==0)
  1. 将您的操作转移到 JavaScript 注入中
 self.driver.execute_script("$(\"li:contains('Narendra')\").click()");
  1. 主动等待元素过时
  # Wait till the element goes stale, this means the list has updated
  wait_until(lambda: is_element_stale(old_link_reference))

该解决方案对我有用,如果您有任何其他适用于您的方案,我在这里提到过,然后在下面发表评论

于 2016-07-13T09:00:46.593 回答
9

尝试等待这样的元素:

// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> stubbornWait = new FluentWait<WebDriver>(driver)
    .withTimeout(30, SECONDS)
    .pollingEvery(5, SECONDS)
    .ignoring(NoSuchElementException.class)
    .ignoring(StaleElementReferenceException.class);

WebElement foo = stubbornWait.until(new Function<WebDriver, WebElement>() {
    public WebElement apply(WebDriver driver) {
        return driver.findElement(By.id("foo"));
    }
});
于 2014-02-11T18:20:39.363 回答
4

StaleElementReferenceException是由于 findelement 方法访问的元素不可用。

您需要在对元素执行任何操作之前确保(如果您对该元素的可用性有疑问)

等待元素的可见性

(new WebDriverWait(driver, 10)).until(new ExpectedCondition()
    {
           public Boolean apply(WebDriver d) {
              return d.findElement(By.name("createForm:dateInput_input")).isDisplayed();
     }});

否则使用逻辑来验证元素是否存在。

于 2013-04-23T11:36:16.567 回答
2

使用 Selenium 提供的预期条件等待 WebElement。

在您调试时,客户端并不像您只运行单元测试或 maven 构建那样快。这意味着在调试模式下,客户端有更多时间准备元素,但如果构建运行相同的代码,他会更快,并且您要查找的 WebElement 在页面的 DOM 中可能不可见。

相信我,我遇到了同样的问题。

例如:

inClient.waitUntil(ExpectedConditions.visibilityOf(YourElement,2000))

这个简单的方法调用在他调用 2 秒后等待您的 WebElement 在 DOM 上的可见性。

于 2013-07-25T13:45:09.587 回答
1

我建议不要将@CachelookUpSelenium WebDriver 用于StaleElementReferenceException.

如果您正在使用@FindByannotation 并且 have @CacheLookUp,只需将其注释掉并检查。

于 2014-07-01T20:33:42.473 回答
1

我已经用下面的代码解决了这个问题。

public WebElement waitForElement(final By findBy, final int waitTime) {
    Wait<AppiumDriver> wait = new FluentWait<>((AppiumDriver) driver)
            .withTimeout(waitTime, TimeUnit.SECONDS)
            .pollingEvery(POLL_TIME, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class,StaleElementReferenceException.class);

    WebElement webElement = wait.until(new Function<AppiumDriver, WebElement>() {
        @Override
        public WebElement apply(AppiumDriver driver) {
            System.out.println("Trying to find element " + findBy.toString());                
            WebElement element = driver.findElement(findBy);
            return element;
        }
    });
    return webElement;
}
于 2015-05-05T23:55:29.913 回答
1

发生陈旧元素异常时!!

当支持这些文本框/按钮/链接的库发生更改时,可能会发生陈旧元素异常,这意味着元素相同,但网站中的引用现在已更改,而不会影响定位器。因此,我们存储在缓存中的引用(包括库引用)现在已经过时或陈旧,因为页面已经用更新的库进行了刷新。

for(int j=0; j<5;j++)
try {
    WebElement elementName=driver.findElement(By.name(“createForm:dateInput_input”));
    break;
} catch(StaleElementReferenceException e){
e.toString();
System.out.println(“Stale element error, trying ::  ” + e.getMessage());
}
elementName.sendKeys(“20/06/2018”);
于 2018-06-25T13:58:05.387 回答
0

这对我有用(来源在这里):

 /**
     * Attempts to click on an element multiple times (to avoid stale element
     * exceptions caused by rapid DOM refreshes)
     *
     * @param d
     *            The WebDriver
     * @param by
     *            By element locator
     */
    public static void dependableClick(WebDriver d, By by)
    {
        final int MAXIMUM_WAIT_TIME = 10;
        final int MAX_STALE_ELEMENT_RETRIES = 5;

        WebDriverWait wait = new WebDriverWait(d, MAXIMUM_WAIT_TIME);
        int retries = 0;
        while (true)
        {
            try
            {
                wait.until(ExpectedConditions.elementToBeClickable(by)).click();

                return;
            }
            catch (StaleElementReferenceException e)
            {
                if (retries < MAX_STALE_ELEMENT_RETRIES)
                {
                    retries++;
                    continue;
                }
                else
                {
                    throw e;
                }
            }
        }
    }
于 2013-08-05T01:46:23.930 回答
0

WebDriver 必须等到元素被定位并且超时是在 10 秒之后。

WebElement myDynamicElement1 = new WebDriverWait(driver, 10).until(
    ExpectedConditions.presenceOfElementLocated(
        By.name("createForm:dateInput_input")
    )
);
于 2014-01-21T08:14:35.537 回答
0

我发现避免过时元素引用的最佳方法是不使用 PageFactory,而是存储定位器(即按元素)。

public class WebDriverFactory {

    // if you want to multithread tests, use a ThreadLocal<WebDriver> 
    // instead.
    // This also makes it so you don't have to pass around WebDriver objects
    // when instantiating new Page classes
    private static WebDriver driver = null;

    public static WebDriver getDriver() {
       return driver;
    }
    public static void setDriver(WebDriver browser)  {
       driver = browser;
    }       
}

// class to let me avoid typing out the lengthy driver.findElement(s) so 
// much
public Abstract class PageBase {
    private WebDriver driver = WebDriverFactory.getDriver();

    // using var args to let you easily chain locators
    protected By getBy(By... locator) {
      return new ByChained(locator);
    }

    protected WebElement find(By... locators) {
      return driver.findElement(getBy(locators));
    }

    protected List<WebElement> findEm(By... locators) {
      return driver.findElements(getBy(locators));
    }

    protected Select select(By... locators) {
      return new Select(getBy(locators));
    }
}

public class somePage extends PageBase {
  private static WebDriver driver = WebDriverFactory.getDriver();
  private static final By buttonBy = By.cssSelector(".btn-primary");

  public void clickButton() {
     WebDriverWait wait = new WebDriverWait(driver, 10);
     wait.until(ExpectedConditions.elementToBeClickable(buttonBy));
     find(buttonBy).click();
  }

}

我有一个充满了我使用的静态 WebDriverWait 方法的类。而且我不记得上面使用 WebDriver wait 是否会处理 StaleElement 异常。如果没有,您可以像 DjangoFan 的回答那样使用流利的等待。但是我所展示的原理将起作用(即使与 WebDriverWait 的那条特定线爆炸了。

所以 tldr;

  1. 使用定位器,以及 WebDriverWait/Fluent 等待/自己重新定位元素的组合,因此如果您的元素过时,您可以重新定位它而无需在@FindBy(对于 pagefactory 初始化的元素)中复制定位器,因为没有 WebElement.relocate () 方法。
  2. 为了简化生活,有一个带有用于定位元素/元素列表的便捷方法的 Abstract BasePage 类。
于 2017-09-15T17:48:45.190 回答
0

就我而言,此错误是由于我在

def parse(self, response):

使用 Selenium 和 Scrapy 组合时的方法,例如:

不起作用:

class MySpider(scrapy.Spider):
     action_chains = ActionChains(self.driver)

移动action_chains = ActionChains(self.driver)内部def parse(self, response):解决了问题,例如:

作品:

def parse(self, response):
     self.driver.get(response.url)
     action_chains = ActionChains(self.driver)
于 2016-11-04T16:03:20.863 回答
0

在对问题进行深入调查后,我发现选择仅为 Bootstrap 添加的 DIV 元素时发生错误。Chrome 浏览器删除此类 DIVS 并发生错误。降级并选择真正的元素来修复错误就足够了。例如,我的模态对话框具有以下结构:

<div class="modal-content" uib-modal-transclude="">
    <div class="modal-header">
        ...
    </div>
    <div class="modal-body">
        <form class="form-horizontal ...">
            ...
        </form>
    <div>
<div>

选择div class="modal-body"会产生错误,选择form ...会正常工作。

于 2016-10-03T13:38:39.390 回答
0

在 Selenium 3 中,您可以使用ExpectedConditions.refreshed(your condition)

它将处理 StaleElementReferenceException 并重试该条件。

于 2021-01-12T19:50:46.987 回答
0

我尝试了上述许多建议,但最简单的一个有效。在我的情况下,是对 web 元素使用 @CachelookUp 导致了过时的元素异常。我猜刷新页面后,元素引用没有重新加载并且找不到元素。为元素禁用 @CachelookUp 行有效。

    //Search button
    @FindBy(how=How.XPATH, using =".//input[@value='Search']")  
    //@CachelookUp
    WebElement BtnSearch;
于 2017-10-25T14:23:01.077 回答
0

这个解决方案对我来说很好:

添加错误处理功能并重试

var pollLoop = function () {
      element(by.id('spinnerElem')).getAttribute('class').then(function (cls) {
                if (cls.indexOf('spinner-active') > -1) {
                    // wait for the spinner
                } else {
                    //do your logic
                    promise.defer().fulfill();
                }
            }, function () {
                // This err handling function is to handle the {StaleElementReferenceError} and makes sure we find the element always.
                pollLoop();
            });
        };
于 2016-07-05T13:14:18.107 回答
0

在带有 for loop EX: for python 的 try catch 块中使用 webdriverwait 和 ExpectedCondition

for i in range(4):
    try:
        element = WebDriverWait(driver, 120).until( \
                EC.presence_of_element_located((By.XPATH, 'xpath')))
        element.click()    
        break
    except StaleElementReferenceException:
        print "exception "
于 2015-09-30T05:35:17.880 回答
-1

如果我们不确定答案,请不要混淆我们自己。这对最终用户来说非常令人沮丧。简单而简短的答案是在 webdriver 中使用 @CacheLookup 注释。请参阅下面的链接。 @CacheLookup 如何在 WebDriver 中工作?

于 2015-04-16T11:19:40.257 回答
-1

参考@djangofan 给出的答案,看起来可行的解决方案是将您的代码保留try catch在可能发生过时的块内。当我使用下面的代码时,我没有任何时候遇到问题。

public void inputName(String name)
{
    try {
        waitForVisibilityElement(name);//My own visibility function
        findElement(By.name("customerName")).sendKeys(name);
    }
    catch (StaleElementReferenceException e)
    {
        e.getMessage();
    }
}

我尝试过使用,ExpectedConditions.presenceOfElementLocated(By)但过时异常仍然间歇性地抛出。

希望这个解决方案有所帮助。

于 2016-03-31T06:07:08.477 回答
-2

只需下载新的 chrome 扩展程序并使用 selenium server 3 即可。

于 2017-06-30T07:45:59.883 回答