Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Selenium 请等待文档准备就绪_Selenium_Load_Document_Wait - Fatal编程技术网

Selenium 请等待文档准备就绪

Selenium 请等待文档准备就绪,selenium,load,document,wait,Selenium,Load,Document,Wait,有人能告诉我如何让selenium等到页面完全加载时再运行吗?我想要一些通用的东西,我知道我可以配置WebDriverWait并调用类似“find”的东西让它等待,但我没有走那么远。我只需要测试页面是否成功加载,然后转到下一个页面进行测试 我在.net中找到了一些东西,但无法在java中运行 IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSecond

有人能告诉我如何让selenium等到页面完全加载时再运行吗?我想要一些通用的东西,我知道我可以配置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"));
IWait wait=new OpenQA.Selenium.Support.UI.WebDriverWait(driver,TimeSpan.FromSeconds(30.00));
wait.Until(driver1=>((IJavaScriptExecutor)driver.ExecuteScript(“return document.readyState”).Equals(“complete”);

有人有什么想法吗?

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

void waitForLoad(WebDriver驱动程序){
新WebDriverWait(驱动程序,30)。直到((预期条件)wd->
((JavascriptExecutor)wd.executeScript(“return document.readyState”).equals(“complete”);
}
c#的示例:

publicstaticvoidwaitforload(IWebDriver驱动程序,int-timeoutSec=15)
{
IJavaScriptExecutor js=(IJavaScriptExecutor)驱动程序;
WebDriverWait wait=新的WebDriverWait(驱动程序,新的时间跨度(0,0,timeoutSec));
等到(wd=>js.ExecuteScript(“return document.readyState”).ToString()==“complete”);
}
PHP示例:

最终公共函数waituntldomreadystate(RemoteWebDriver$webDriver):无效
{
$webDriver->wait()->until(函数(){
return$webDriver->executeScript('return document.readyState')=='complete';
});
}

尝试以下代码:

  driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
上述代码将等待长达10秒的页面加载。如果页面加载超过时间,它将抛出
TimeoutException
。你抓住了这个例外并满足了你的需求。我不确定它是否在抛出异常后退出页面加载。我还没有尝试这个代码。我想试试看

这是一种隐含的等待。如果设置一次,它将具有作用域,直到Web驱动程序实例销毁


有关更多信息,请参阅。

您建议的解决方案仅等待信号
完成。但是默认情况下,Selenium会尝试通过和方法等待页面上的加载(以及更多)。他们已经阻塞,他们等待页面完全加载,这些应该可以正常工作

显然,问题在于通过AJAX请求和运行脚本的重定向——Selenium无法捕获这些重定向,它不会等待它们完成。此外,您无法通过
readyState
可靠地捕获它们-它会等待一段时间,这可能很有用,但它会在下载所有AJAX内容之前发出
完成的信号

没有一个通用的解决方案可以适用于所有地方和每个人,这就是为什么它很难,每个人都使用一些不同的东西

一般的规则是依靠WebDriver完成自己的工作,然后使用隐式等待,然后使用显式等待,等待您想要在页面上断言的元素,但是还有很多技术可以完成。你应该在你的测试页面上选择一个(或几个的组合)在你的情况下效果最好

有关更多信息,请参见我的两个答案:

公共无效waitForPageToLoad()
{
(新WebDriverWait(驱动程序,默认等待时间))。直到(新的ExpectedCondition(){
公共布尔应用(WebDriver d){
return((org.openqa.selenium.JavascriptExecutor)driver.executeScript(“return document.readyState”).equals(“complete”);
}
});//这里默认的_WAIT _TIME是一个整数,对应于以秒为单位的等待时间

您可以编写一些逻辑来处理此问题。我已经编写了一个方法,该方法将返回
WebElement
,此方法将被调用三次,或者您可以增加时间并为
WebElement
添加空检查。下面是一个示例

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;
        }
    }
publicstaticvoidmain(字符串[]args){
WebDriver=newfirefoxdriver();
驱动程序。获取(“https://www.crowdanalytix.com/#home");
WebElement WebElement=getWebElement(驱动程序,“homekkk”);
int i=1;
while(webElement==null&&i<4){
webElement=getWebElement(驱动程序,“homessss”);
System.out.println(“调用”);
i++;
}
System.out.println(webElement.getTagName());
系统输出打印项次(“结束”);
driver.close();
}
公共静态WebElement getWebElement(WebDriver驱动程序,字符串id){
WebElement myDynamicElement=null;
试一试{
myDynamicElement=(新的WebDriverWait(驱动程序,10))
.直到(预期条件)找到的元素的存在
.id(id));
返回动态加速;
}捕获(TimeoutException例外){
返回null;
}
}

以下是我在Python中尝试的一个完全通用的解决方案:

首先,一个通用的“wait”函数(如果您愿意,可以使用WebDriverWait,我觉得它们很难看):

要获得更多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)
然后您可以在几乎任何selenium交互上使用它:

with wait_for_page_load(browser):
    browser.find_element_by_link_text('my link').click()
我想那是防弹的!你觉得呢


更多信息,请参见红宝石:

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

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

替换:

AppDriver.Navigate().GoToUrl(url);
与:

而不是使用:

OpenURL(myDriver, myUrl);
这将加载页面,等待完成,最大化并专注于它。我不知道为什么它是这样,但它的工作


如果您想在单击“下一步”或任何其他页面导航触发后等待页面加载,然后单击“导航()”,Ben Dyer的回答(在此线程中)将完成此工作。

我遇到了类似的问题。我需要等待文档准备就绪,但也需要等待所有Ajax调用完成。第二个条件是
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
wait.until { @driver.execute_script('return document.readyState').eql?('complete') }
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);
return (document.readyState == 'complete' && jQuery.active == 0)
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);
}
<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>
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
    }          
}
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();
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();
WebDriverWait wait = new WebDriverWait(dr, 30);
wait.until(ExpectedConditions.jsReturnsValue("return document.readyState==\"complete\";"));
Predicate<WebDriver> pageLoaded = wd -> ((JavascriptExecutor) wd).executeScript(
        "return document.readyState").equals("complete");
new FluentWait<WebDriver>(driver).until(pageLoaded);
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);
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");
}
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; 
        }   
      }
 }
driver.get('www.sidanmor.com').then(()=> {
    // here the page is fully loaded!!!
    // do your stuff...
}).catch(console.log.bind(console));
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...
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;
    }
 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");
    }
 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"));

}
    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.");
    }
}
  private static boolean isloadComplete(WebDriver driver)
    {
        return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("loaded")
                || ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
    }
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);
}
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.presenceOfAllElementsLocated(By.xpath("//*")));
    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);
        }
    }
public static void WaitForElement(IWebDriver driver, By element)
{
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
    wait.Until(ExpectedConditions.ElementIsVisible(element));
}
WaitForElement(driver, By.ClassName("error-message"));