Selenium: How to tell if RemoteWebDriver.findElements(By) can throw StaleElementReferenceException at all?

后端 未结 2 1991
面向向阳花
面向向阳花 2020-11-28 16:44

In my understanding such exception can be thrown only if the code operates on a WebElement instance, calling methods on it after the corresponding DOM element h

2条回答
  •  臣服心动
    2020-11-28 17:28

    You pinpointed issue about "StaleElementReferenceException", this is related when webElement instances changes, when DOM is changed due some activity on page.

    It is related to how WebDriver internally handles references to webElements, and this issue happens when during runtime references to object(s) are changed.

    Now, let’s assume when you have fetched the element and before doing any action on it, something got refreshed on your page. It could be the whole page that is being refreshed or some call which has refreshed only a section of the DOM where your element falls.

    In this scenario the internal id which WebDriver was using, and stored somewhere in cache has become stale (not referenced anymore), so now for every operation on this WebElement, we will get StaleElementReferenceException.

    So to try to avoid it on critical places try to use this method, for determine if element is stale.

    public static boolean isStale(WebElement e){
        try{
            e.isDisplayed();
            return false;
        }catch(StaleElementReferenceException ex){
            return true;
        }
    }
    

    Usually refreshing of page, pageObject, or just this particular element would help in 90% of cases.

    And after refreshing page/element WebDriver will assign a different internal Id to this element, and will be able to use it again without any problem.

    This problem is solver with PageObject / PageFactory design patter.

    public class SomePage {
        @FindBy(how = How.NAME, using = "q")
        private WebElement searchBox;
    
    
        public SomePage() {
            PageFactory.initElements(driver, this);
        }
    
    
        public void searchFor(String text) {
            searchBox.sendKeys(text);
        }
    }
    

    Hope this helps,

提交回复
热议问题