Selenium WebDriver - 如何使用 C# 设置页面加载超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10606703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:29:06  来源:igfitidea点击:

Selenium WebDriver - How to set Page Load Timeout using C#

c#seleniumtimeoutwebdriverwait

提问by KabanaSoft

I am using Selenium 2.20 WebDriver to create and manage a firefox browser with C#. To visit a page, i use the following code, setting the driver timeouts before visiting the URL:

我正在使用 Selenium 2.20 WebDriver 创建和管理带有 C# 的 firefox 浏览器。要访问页面,我使用以下代码,在访问 URL 之前设置驱动程序超时:

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5)); // Set implicit wait timeouts to 5 secs
driver.Manage().Timeouts().SetScriptTimeout(new TimeSpan(0, 0, 0, 5));  // Set script timeouts to 5 secs
driver.Navigate().GoToUrl(myUrl);   // Goto page url

The problem is that sometimes pages take forever to load, and it appears that the default timeout for a page to load using the selenium WebDriver is 30 seconds, which is too long. And i don't believe the timeouts i am setting apply to the loading of a page using the GoToUrl() method.

问题是有时页面需要永远加载,而且使用 selenium WebDriver 加载页面的默认超时时间似乎是 30 秒,这太长了。而且我不相信我设置的超时适用于使用 GoToUrl() 方法加载页面。

So I am trying to figure out how to set a timeout for a page to load, however, i cannot find any property or method that actually works. The default 30 second timeout also seems to apply to when i click an element.

所以我试图弄清楚如何设置页面加载超时,但是,我找不到任何实际有效的属性或方法。当我单击一个元素时,默认的 30 秒超时似乎也适用。

Is there a way to set the page load timeout to a specific value so that when i call the GoToUrl() method it will only wait my specified time before continuing?

有没有办法将页面加载超时设置为特定值,以便当我调用 GoToUrl() 方法时,它只会在继续之前等待我指定的时间?

回答by Amey

With this you should be able to declare a wait explicitly.

有了这个,您应该能够明确声明等待。

WebDriverWait wait = new WebDriverWait(browser, new TimeSpan(time in seconds));
wait.until(Your condition)

you could also change the implicit wait time

您还可以更改隐式等待时间

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

I think that is the syntax in C#. (not to sure)

我认为这是 C# 中的语法。(不确定)

In ruby it is

在红宝石中它是

@driver.manage.timeouts.implicit_wait = 30
@wait = Selenium::WebDriver::Wait.new(:timeout => 30)

回答by JimEvans

Page load timeouts are not implemented in the .NET bindings yet. Hopefully they will be soon.

.NET 绑定中尚未实现页面加载超时。希望他们会很快。

回答by KabanaSoft

i found the solution this this issue. When creating a new FirefoxDriver, there are overloads in the constructor that allow you to specify a command timeout which is the maximum time to wait for each command, and it seems to be working when calling the GoToUrl() method:

我找到了这个问题的解决方案。创建新的 FirefoxDriver 时,构造函数中有重载允许您指定命令超时,即等待每个命令的最长时间,并且在调用 GoToUrl() 方法时似乎可以正常工作:

driver = new FirefoxDriver(new FirefoxBinary(), profile, new TimeSpan(0, 0, 0, timeoutSeconds));

link to FirefoxDriver constructor documentation for reference: http://selenium.googlecode.com/svn/trunk/docs/api/dotnet/html/M_OpenQA_Selenium_Firefox_FirefoxDriver__ctor_2.htm

链接到 FirefoxDriver 构造函数文档以供参考:http://selenium.googlecode.com/svn/trunk/docs/api/dotnet/html/M_OpenQA_Selenium_Firefox_FirefoxDriver__ctor_2.htm

Hope this helps someone else who runs into this problem.

希望这可以帮助遇到此问题的其他人。

回答by ktam33

In case this helps anyone still looking for the answer to this, the C# WebDriver API now contains the appropriate method.

如果这有助于任何仍在寻找答案的人,C# WebDriver API 现在包含适当的方法。

driver.Manage().Timeouts().SetPageLoadTimeout(timespan)

回答by Josh

driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(5);

Note: driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(5))is now deprecated.

注意:driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(5))现在已弃用。

回答by Ywapom

As of 2018: Besides these:

截至 2018 年:除此之外:

driver.Manage().Timeouts().ImplicitWait.Add(System.TimeSpan.FromSeconds(5));      
driver.Manage().Timeouts().PageLoad.Add(System.TimeSpan.FromSeconds(5));
driver.Manage().Timeouts().AsynchronousJavaScript.Add(timespan));

wait for searching for an item, loading a page, and waiting for script respectively. There is:

分别等待搜索项目、加载页面和等待脚本。有:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

回答by Marko Marchiori

We brazilians have a word for crappy workarounds "Gambiarra"... Well... at least they do the job... Here is mine:

我们巴西人有一个词来形容蹩脚的变通办法“Gambiarra”……好吧……至少他们完成了这项工作……这是我的:

var url = "www.your.url.here"
try {
    DRIVER.Navigate().GoToUrl(url);
} catch {
    // Here you can freely use the Selenium's By class:
    WaitElement(By.Id("element_id_or_class_or_whatever_to_be_waited"), 60);
}
// rest of your application

What my WaitElement(By, int)does:

我的WaitElement(By, int)工作:

/// <summary>
/// Waits until an element of the type <paramref name="element"/> to show in the screen.
/// </summary>
/// <param name="element">Element to be waited for.</param>
/// <param name="timeout">How long (in seconds) it should be waited for.</param>
/// <returns>
/// False: Never found the element. 
/// True: Element found.
/// </returns>
private bool WaitElement(By element, int timeout)
{
    try {
        Console.WriteLine($" - Waiting for the element {element.ToString()}");
        int timesToWait = timeout * 4; // Times to wait for 1/4 of a second.
        int waitedTimes = 0; // Times waited.
        // This setup timesout at 7 seconds. you can change the code to pass the 

        do {
            waitedTimes++;
            if (waitedTimes >= timesToWait) {
                Console.WriteLine($" -- Element not found within (" +
                $"{(timesToWait * 0.25)} seconds). Canceling section...");
                return false;
            }
            Thread.Sleep(250);
        } while (!ExistsElement(element));

        Console.WriteLine($" -- Element found. Continuing...");
    //  Thread.Sleep(1000); // may apply here
        return true;
    } catch { throw; }
}

After this, you can play with timeout...

在此之后,您可以玩timeout...

Make Bythe things you notice that loads last in the page (like javascript elements and captchas) remembering: it will start working the // rest of your applicationbefore the page fully loads, therefore may be nice to put a Thread.Sleep(1000)at the end just to be sure...

使By您注意到的内容最后加载到页面中(如 javascript 元素和验证码)记住:它将// rest of your application在页面完全加载之前开始工作,因此最好Thread.Sleep(1000)在最后放置一个以确保...

Also notice that this method will be called AFTER the 60 seconds standard timeout from Selenium's DRIVER.Navigate().GoToUrl(url);

另请注意,此方法将在 Selenium 的 60 秒标准超时后调用 DRIVER.Navigate().GoToUrl(url);

Not the best, but... as I said: A good gambiarra gets the job done...

不是最好的,但是......正如我所说:一个好的 gambiarra 完成工作......

回答by T. Muir

driver.Manage().Timeouts().SetPageLoadTimeout(timespan) 

does not work.

不起作用。

This works. Use a property setter syntax.

这有效。使用属性设置器语法。

driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(15);

回答by imba-tjd

For anyone who wants the opposite effect: setting timeout longer than 60s.

对于任何想要相反效果的人:设置超时时间超过 60 秒。

You need both use:

您需要同时使用:

new FirefoxDriver(FirefoxDriverService.CreateDefaultService(), new FirefoxOptions(), TimeSpan.FromSeconds(120))

and

driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(120);

The new FirefoxDriver(binary, profile, timeSpan)has been obsolete.

new FirefoxDriver(binary, profile, timeSpan)已经过时。