首页 文章

Selenium等到文档准备好了

提问于
浏览
111

任何人都可以让我如何让硒等到页面完全加载的时候?我想要一些通用的东西,我知道我可以配置WebDriverWait并调用类似'find'的东西让它等待,但我不会那么远 . 我只需要测试页面加载成功并转到下一页进行测试 .

我在.net中找到了一些东西但是无法在java中使用它...

IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));
wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));

有人想过吗?

26 回答

  • 1

    Try this code:

    driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
    

    上面的代码将等待最多10秒的页面加载 . 如果页面加载超过它将抛出 TimeoutException 的时间 . 你 grab 了例外,满足了你的需求 . 我不确定是否在抛出异常后退出页面加载 . 我还没有尝试这个代码 . 想要尝试一下 .

    这是一个隐含的等待 . 如果你设置了一次它将具有范围,直到Web驱动程序实例销毁 .

    更多info.

  • 0

    您建议的解决方案仅等待DOM readyState发出 complete 信号 . 但Selenium默认尝试通过driver.get()element.click()方法等待页面加载(并且多一点) . 他们已经阻止,他们等待页面完全加载,那些应该正常工作 .

    显然,问题是通过AJAX请求和运行脚本重定向 - 那些可以等待它们完成 . 此外,您无法通过 readyState 可靠地捕获它们 - 它等待一点,这可能很有用,但它会在下载所有AJAX内容之前发出 complete 信号 .

    没有通用的解决方案可以在任何地方和每个人工作,这就是为什么它很难,每个人都使用一些不同的东西 .

    一般规则是依靠WebDriver来完成他的工作,然后使用隐式等待,然后使用显式等待你想在页面上断言的元素,但是还有更多的技术可以完成 . 您应该在测试页面上选择最适合您情况的一个(或其中几个组合) .

    有关详细信息,请参阅我的两个答案:

  • 72

    这是您给出的示例的可用Java版本:

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

    示例对于c#:

    public static void WaitForLoad(IWebDriver driver, int timeoutSec = 15)
    {
      IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
      WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, timeoutSec));
      wait.Until(wd => js.ExecuteScript("return document.readyState").ToString() == "complete");
    }
    
  • 81

    这是我在Python中尝试完全通用的解决方案:

    首先,一个通用的“等待”函数(如果你愿意,可以使用WebDriverWait,我发现它们很难看):

    def wait_for(condition_function):
        start_time = time.time()
        while time.time() < start_time + 3:
            if condition_function():
                return True
            else:
                time.sleep(0.1)
        raise Exception('Timeout waiting for {}'.format(condition_function.__name__))
    

    接下来,解决方案依赖于selenium为页面上的所有元素记录(内部)id号的事实,包括顶级 <html> 元素 . 当页面刷新或加载时,它会获得一个带有新ID的新html元素 .

    因此,假设您要单击带有文本“我的链接”的链接,例如:

    old_page = browser.find_element_by_tag_name('html')
    
    browser.find_element_by_link_text('my link').click()
    
    def page_has_loaded():
        new_page = browser.find_element_by_tag_name('html')
        return new_page.id != old_page.id
    
    wait_for(page_has_loaded)
    

    对于更多Pythonic,可重用的通用助手,您可以创建一个上下文管理器:

    from contextlib import contextmanager
    
    @contextmanager
    def wait_for_page_load(browser):
        old_page = browser.find_element_by_tag_name('html')
    
        yield
    
        def page_has_loaded():
            new_page = browser.find_element_by_tag_name('html')
            return new_page.id != old_page.id
    
        wait_for(page_has_loaded)
    

    然后你可以在任何硒交互中使用它:

    with wait_for_page_load(browser):
        browser.find_element_by_link_text('my link').click()
    

    我认为那是防弹的!你怎么看?

    更多信息blog post about it here

  • 7

    我遇到了类似的问题 . 我需要等到我的文档准备就绪,直到所有Ajax调用完成 . 事实证明第二个条件很难被发现 . 最后,我检查了活动的Ajax调用,并且它工作正常 .

    使用Javascript:

    return (document.readyState == 'complete' && jQuery.active == 0)
    

    完整的C#方法:

    private void WaitUntilDocumentIsReady(TimeSpan timeout)
    {
        var javaScriptExecutor = WebDriver as IJavaScriptExecutor;
        var wait = new WebDriverWait(WebDriver, timeout);            
    
        // Check if document is ready
        Func<IWebDriver, bool> readyCondition = webDriver => javaScriptExecutor
            .ExecuteScript("return (document.readyState == 'complete' && jQuery.active == 0)");
        wait.Until(readyCondition);
    }
    
  • 0
    WebDriverWait wait = new WebDriverWait(dr, 30);
    wait.until(ExpectedConditions.jsReturnsValue("return document.readyState==\"complete\";"));
    
  • -1

    对于C#NUnit,您需要将WebDriver转换为JSExecuter,然后执行脚本以检查document.ready状态是否完整 . 请查看以下代码以供参考:

    public static void WaitForLoad(IWebDriver driver)
        {
            IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
            int timeoutSec = 15;
            WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, timeoutSec));
            wait.Until(wd => js.ExecuteScript("return document.readyState").ToString() == "complete");
        }
    

    这将等到条件满足或超时 .

  • -1

    对于初始页面加载,我注意到“最大化”浏览器窗口实际上等待页面加载完成(包括源)

    更换:

    AppDriver.Navigate().GoToUrl(url);
    

    附:

    public void OpenURL(IWebDriver AppDriver, string Url)
                {
                    try
                    {
                        AppDriver.Navigate().GoToUrl(Url);
                        AppDriver.Manage().Window.Maximize();
                        AppDriver.SwitchTo().ActiveElement();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERR: {0}; {1}", e.TargetSite, e.Message);
                        throw;
                    }
                }
    

    比使用:

    OpenURL(myDriver, myUrl);
    

    这将加载页面,等到完成,最大化并专注于它 . 我不知道为什么会这样,但它有效 .

    如果您想在点击下一个或任何其他页面导航触发器之后等待页面加载,那么“导航()”,Ben Dyer的答案(在此线程中)将完成工作 .

  • 0

    看看tapestry web-framework . 你可以在那里download source code .

    这个想法是通过body的html属性来表示页面已经准备就绪 . 你可以使用这个想法忽略复杂的诉讼案件 .

    <html>
    <head>
    </head>
    <body data-page-initialized="false">
        <p>Write you page here</p>
    
        <script>
        $(document).ready(function () {
            $(document.body).attr('data-page-initialized', 'true');
        });
        </script>  
    </body>
    </html>
    

    然后创建Selenium webdriver的扩展(根据tapestry框架)

    public static void WaitForPageToLoad(this IWebDriver driver, int timeout = 15000)
    {
        //wait a bit for the page to start loading
        Thread.Sleep(100);
    
        //// In a limited number of cases, a "page" is an container error page or raw HTML content
        // that does not include the body element and data-page-initialized element. In those cases,
        // there will never be page initialization in the Tapestry sense and we return immediately.
        if (!driver.ElementIsDisplayed("/html/body[@data-page-initialized]"))
        {                
            return;
        }
    
        Stopwatch stopwatch = Stopwatch.StartNew();
    
        int sleepTime = 20;
    
        while(true)
        {
            if (driver.ElementIsDisplayed("/html/body[@data-page-initialized='true']"))
            {
                return;
            }
    
            if (stopwatch.ElapsedMilliseconds > 30000)
            {
                throw new Exception("Page did not finish initializing after 30 seconds.");
            }
    
            Thread.Sleep(sleepTime);
            sleepTime *= 2; // geometric row of sleep time
        }          
    }
    

    使用扩展名ElementIsDisplayed written by Alister Scott .

    public static bool ElementIsDisplayed(this IWebDriver driver, string xpath)
    {
        try
        {
            return driver.FindElement(By.XPath(xpath)).Displayed;
        }
        catch(NoSuchElementException)
        {
            return false;
        }
    }
    

    最后创建测试:

    driver.Url = this.GetAbsoluteUrl("/Account/Login");            
    driver.WaitForPageToLoad();
    
  • 10

    Ben Dryer 's answer didn' t在我的机器上编译( "The method until(Predicate<WebDriver>) is ambiguous for the type WebDriverWait" ) .

    使用Java 8版:

    Predicate<WebDriver> pageLoaded = wd -> ((JavascriptExecutor) wd).executeScript(
            "return document.readyState").equals("complete");
    new FluentWait<WebDriver>(driver).until(pageLoaded);
    

    Java 7版本:

    Predicate<WebDriver> pageLoaded = new Predicate<WebDriver>() {
    
            @Override
            public boolean apply(WebDriver input) {
                return ((JavascriptExecutor) input).executeScript("return document.readyState").equals("complete");
            }
    
    };
    new FluentWait<WebDriver>(driver).until(pageLoaded);
    
  • 1

    我试过这个代码,它对我有用 . 每次移动到另一页时我都会调用此函数

    public static void waitForPageToBeReady() 
    {
        JavascriptExecutor js = (JavascriptExecutor)driver;
    
        //This loop will rotate for 100 times to check If page Is ready after every 1 second.
        //You can replace your if you wants to Increase or decrease wait time.
        for (int i=0; i<400; i++)
        { 
            try 
            {
                Thread.sleep(1000);
            }catch (InterruptedException e) {} 
            //To check page ready state.
    
            if (js.executeScript("return document.readyState").toString().equals("complete"))
            { 
                break; 
            }   
          }
     }
    
  • 3

    在Nodejs中,您可以通过承诺获得它...

    如果您编写此代码,则可以确保在到达当时页面已完全加载...

    driver.get('www.sidanmor.com').then(()=> {
        // here the page is fully loaded!!!
        // do your stuff...
    }).catch(console.log.bind(console));
    

    如果您编写此代码,您将导航,selenium将等待3秒......

    driver.get('www.sidanmor.com');
    driver.sleep(3000);
    // you can't be sure that the page is fully loaded!!!
    // do your stuff... hope it will be OK...
    

    来自Selenium文档:

    this.get(url)→那么

    安排命令导航到给定的URL .

    返回当文档具有 finished loading 时将解析的promise .

    Selenium Documentation (Nodejs)

  • 1

    等待document.ready事件并不是解决此问题的全部方法,因为此代码仍处于竞争状态:有时在处理单击事件之前触发此代码,因此直接返回,因为浏览器尚未启动正在加载新页面 .

    经过一番搜索后,我在Obay the testing goat找到了一个帖子,该帖子解决了这个问题 . 该解决方案的c#代码是这样的:

    IWebElement page = null;
     ...
     public void WaitForPageLoad()
     {
        if (page != null)
        {
           var waitForCurrentPageToStale = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
           waitForCurrentPageToStale.Until(ExpectedConditions.StalenessOf(page));
        }
    
        var waitForDocumentReady = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
        waitForDocumentReady.Until((wdriver) => (driver as IJavaScriptExecutor).ExecuteScript("return document.readyState").Equals("complete"));
    
        page = driver.FindElement(By.TagName("html"));
    
    }
    

    `我在driver.navigate.gotourl之后直接触发这个方法,以便它尽快得到页面的引用 . 玩得开心!

  • 53

    当selenium从点击或提交或获取方法打开一个新页面时,它会等待untell页面被加载,但问题是当页面有xhr调用(ajax)时他永远不会等待加载xhr,所以创建一个新的方法来监控xhr并等待它们将是好事 . (抱歉我的英文不好:D)

    public boolean waitForJSandJQueryToLoad() {
        WebDriverWait wait = new WebDriverWait(webDriver, 30);
        // wait for jQuery to load
        ExpectedCondition<Boolean> jQueryLoad = new ExpectedCondition<Boolean>() {
          @Override
          public Boolean apply(WebDriver driver) {
            try {
                Long r = (Long)((JavascriptExecutor)driver).executeScript("return $.active");
                return r == 0;
            } catch (Exception e) {
                LOG.info("no jquery present");
                return true;
            }
          }
        };
    
        // wait for Javascript to load
        ExpectedCondition<Boolean> jsLoad = new ExpectedCondition<Boolean>() {
          @Override
          public Boolean apply(WebDriver driver) {
            return ((JavascriptExecutor)driver).executeScript("return document.readyState")
            .toString().equals("complete");
          }
        };
    
      return wait.until(jQueryLoad) && wait.until(jsLoad);
    }
    

    如果$ .active == 0那么没有活动的xhrs调用(仅适用于jQuery) . 对于javascript ajax调用,你必须在项目中创建一个变量并进行模拟 .

  • 0

    你可以编写一些逻辑来处理这个问题 . 我已经编写了一个返回 WebElement 的方法,这个方法将被调用三次,或者你可以增加时间并为_1511761添加一个空检查 . 这是一个例子

    public static void main(String[] args) {
            WebDriver driver = new FirefoxDriver();
            driver.get("https://www.crowdanalytix.com/#home");
            WebElement webElement = getWebElement(driver, "homekkkkkkkkkkkk");
            int i = 1;
            while (webElement == null && i < 4) {
                webElement = getWebElement(driver, "homessssssssssss");
                System.out.println("calling");
                i++;
            }
            System.out.println(webElement.getTagName());
            System.out.println("End");
            driver.close();
        }
    
        public static WebElement getWebElement(WebDriver driver, String id) {
            WebElement myDynamicElement = null;
            try {
                myDynamicElement = (new WebDriverWait(driver, 10))
                        .until(ExpectedConditions.presenceOfElementLocated(By
                                .id(id)));
                return myDynamicElement;
            } catch (TimeoutException ex) {
                return null;
            }
        }
    
  • 4

    我执行了一个javascript代码来检查文档是否准备好了 . 节省了我很多时间为具有客户端渲染的站点调试selenium测试 .

    public static boolean waitUntilDOMIsReady(WebDriver driver) {
    def maxSeconds = DEFAULT_WAIT_SECONDS * 10
    for (count in 1..maxSeconds) {
        Thread.sleep(100)
        def ready = isDOMReady(driver);
        if (ready) {
            break;
        }
    }
    

    }

    public static boolean isDOMReady(WebDriver driver){
        return driver.executeScript("return document.readyState");
    }
    
  • 1
    public boolean waitForElement(String zoneName, String element, int index, int timeout) {
            WebDriverWait wait = new WebDriverWait(appiumDriver, timeout/1000);
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(element)));
            return true;
        }
    
  • -1

    就像Rubanov为C#写的一样,我用Java编写它,它是:

    public void waitForPageLoaded() {
        ExpectedCondition<Boolean> expectation = new
                ExpectedCondition<Boolean>() {
                    public Boolean apply(WebDriver driver) {
                        return (((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals("complete")&&((Boolean)((JavascriptExecutor)driver).executeScript("return jQuery.active == 0")));
                    }
                };
        try {
            Thread.sleep(100);
            WebDriverWait waitForLoad = new WebDriverWait(driver, 30);
            waitForLoad.until(expectation);
        } catch (Throwable error) {
            Assert.fail("Timeout waiting for Page Load Request to complete.");
        }
    }
    
  • 0

    在Java中,它将在下面: -

    private static boolean isloadComplete(WebDriver driver)
        {
            return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("loaded")
                    || ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
        }
    
  • 0

    以下代码应该可以工作:

    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until(ExpectedConditions.presenceOfAllElementsLocated(By.xpath("//*")));
    
  • -3

    对于需要等待特定元素出现的人 . (用过c#)

    public static void WaitForElement(IWebDriver driver, By element)
    {
        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
        wait.Until(ExpectedConditions.ElementIsVisible(element));
    }
    

    然后,如果您想要等待例如DOM中存在class =“error-message”,您只需执行以下操作:

    WaitForElement(driver, By.ClassName("error-message"));
    

    对于id,它将是

    WaitForElement(driver, By.Id("yourid"));

  • 1
    public void waitForPageToLoad()
      {
    (new WebDriverWait(driver, DEFAULT_WAIT_TIME)).until(new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return (((org.openqa.selenium.JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete"));
          }
        });//Here DEFAULT_WAIT_TIME is a integer correspond to wait time in seconds
    
  • 1

    Ruby中有类似的东西:

    wait = Selenium::WebDriver::Wait.new(:timeout => 10)
    wait.until { @driver.execute_script('return document.readyState').eql?('complete') }
    
  • 6

    您可以让线程休眠直到重新加载页面 . 这不是最佳解决方案,因为您需要估计页面加载的时间 .

    driver.get(homeUrl); 
    Thread.sleep(5000);
    driver.findElement(By.xpath("Your_Xpath_here")).sendKeys(userName);
    driver.findElement(By.xpath("Your_Xpath_here")).sendKeys(passWord);
    driver.findElement(By.xpath("Your_Xpath_here")).click();
    
  • 0

    我检查页面加载完成,在Selenium 3.14.0中工作

    public static void UntilPageLoadComplete(IWebDriver driver, long timeoutInSeconds)
        {
            Until(driver, (d) =>
            {
                Boolean isPageLoaded = (Boolean)((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete");
                if (!isPageLoaded) Console.WriteLine("Document is loading");
                return isPageLoaded;
            }, timeoutInSeconds);
        }
    
        public static void Until(IWebDriver driver, Func<IWebDriver, Boolean> waitCondition, long timeoutInSeconds)
        {
            WebDriverWait webDriverWait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
            webDriverWait.Timeout = TimeSpan.FromSeconds(timeoutInSeconds);
            try
            {
                webDriverWait.Until(waitCondition);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    
  • -1

    你在使用Angular吗?如果您是,webdriver可能无法识别异步调用已完成 .

    我建议看Paul Hammants ngWebDriver . waitForAngularRequestsToFinish()方法可以派上用场 .

相关问题