简体   繁体   English

页面加载超时 - 使用C#的Selenium Webdriver

[英]Page Load Timeout - Selenium Webdriver using C#

I am using Selenium 2.25 WebDriver 我正在使用Selenium 2.25 WebDriver

I'm having a issue with finding the elements on the page and some times my test cases able to find element and sometime the page is does not load and its due to page load and if i add this below line and it seems like working: 我遇到了在页面上找到元素的问题,有时候我的测试用例能够找到元素,有时页面不会加载,而且由于页面加载,如果我在下面添加这个元素,它似乎正在工作:

 driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(2));

my question is, i dont want to have my code scatter with the above line of code, is there a way to make it centerlize in one place? 我的问题是,我不想让我的代码散布上面的代码行,有没有办法让它在一个地方集中化?

Any help would be greatly appreciated, thanks! 任何帮助将不胜感激,谢谢!

If you set the timeout once, it's set for the lifetime of the driver instance. 如果设置超时一次,则将其设置为驱动程序实例的生命周期。 You don't need to keep resetting it. 您无需继续重置它。 You can set this immediately after creating the driver. 您可以在创建驱动程序后立即设置此项。

IWebDriver driver = new FirefoxDriver();
driver.Manage().Timeouts.SetPageLoadTimeout(TimeSpan.FromSeconds(2));

The only caveat for using this timeout is that not every browser may support it completely (IE does for sure, Firefox does too I think, but I don't think Chrome does). 使用此超时的唯一警告是,并非每个浏览器都可以完全支持它(IE确实如此,我认为Firefox也是如此,但我不认为Chrome会这样做)。

You can try a workaround like this: 您可以尝试这样的解决方法:

Observe the element that loads last in your page and find its id (or any other identifier). 观察页面中最后加载的元素并查找其ID(或任何其他标识符)。 Then do something like this: 然后做这样的事情:

 while (true)
        {
            try
            {   
                IWebElement element = driver.FindElement(By.Id(...));
                if (element.Displayed)
                {
                    break;
                }
            }
            catch (Exception)
            {
                continue;
            }
        }

This will keep looping till the element which is loaded last is displayed and breaks thereupon. 这将保持循环,直到显示最后加载的元素并在其上断开。 The element not found exception is caught and loop is put into continuation till the element is not displayed. 捕获元素未找到异常并将循环置于延续中直到元素未显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM