首页 文章

Selenium Java(正确等待加载新页面)

提问于
浏览
0

这不是一个问题,而是一个信息的共享(我想很多人会使用它)

几天试图制作一个最好的解决方案(没有sheninigans :-D)等待新页面加载,点击后等.ofc没有旧时Thread.sleep或隐式等待

有些人建议等到新页面的最后一个元素加载,有些人建议使用JS Actuator (document.readyState解决方案),这有时不起作用(在我的情况下,它总是提供完整的响应)

找到另一个解决方案,检查当前页面上对元素的引用何时会抛出StaleElementReferenceException . 但是......在这种情况下,页面无法在此异常后加载 .

我做了什么?将这两个解决方案结合在一起,这对我来说总是很有用......一个确保文档没有处于就绪状态(导致抛出staleElementReferenceException),另一个确保文件完全加载后直到页面完全加载并给出readyState ==完成

while(true) {    
       try {
          //it's just an interaction (can be any) with element on current page
          anyElementFromCurrentPage.getText();
       } catch (StaleElementReferenceException e) {
            break;
       }
       waitForLoad(driver);
       return this;
    }

    void waitForLoad(WebDriver driver) {
       new WebDriverWait(driver, 30).until((ExpectedCondition<Boolean>) wd ->
                    ((JavascriptExecutor) wd).executeScript("return 
       document.readyState").equals("complete"));
    }

希望有些人会使用这个防弹解决方案:-)

1 回答

  • 0

    所以我在C#中工作,但Java类似 . 这是我使用的,即使它被标记为“过时” .

    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
    wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Name("elementNameHere")));
    

相关问题