Java 如何设置 selenium webdriver 获取超时?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9731291/
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-16 06:50:42  来源:igfitidea点击:

How do I set the selenium webdriver get timeout?

javaseleniumwebdriver

提问by u627670

When I am using a proxy in webdriver like FirefoxDriver, if the proxy is bad then the get method will block forever. I set some timeout parameters, but this did not work out.

当我在像 FirefoxDriver 这样的 webdriver 中使用代理时,如果代理坏了,那么 get 方法将永远阻塞。我设置了一些超时参数,但这没有奏效。

This is my code:

这是我的代码:

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("general.useragent.override", ua);    
Proxy p = new Proxy();
p.setHttpProxy(proxy);
profile.setProxyPreferences(p);
profile.setEnableNativeEvents(true);

// create a driver
WebDriver driver = new FirefoxDriver(profile);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
driver.get("www.sina.com.cn")

The call to driver.get will block for ever, but I want it to wait for 30 seconds and if the page is not loaded then throw an exception.

对 driver.get 的调用将永远阻塞,但我希望它等待 30 秒,如果页面未加载,则抛出异常。

采纳答案by Fujiao Liu

Try this:

尝试这个:

 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

回答by user1102631

The timeouts()methods are not implemented in some drivers and are very unreliable in general.
I use a separate thread for the timeouts (passing the url to access as the thread name):

这些timeouts()方法在某些驱动程序中未实现,并且通常非常不可靠。
我为超时使用了一个单独的线程(将 url 作为线程名称传递给访问):

    Thread t = new Thread(new Runnable()
    {
      public void run()
      {
        driver.get(Thread.currentThread().getName());
      }
    }, url);
    t.start();
    try
    {
      t.join(YOUR_TIMEOUT_HERE_IN_MS);
    }
    catch (InterruptedException e)
    { // ignore
    }
    if (t.isAlive())
    { // Thread still alive, we need to abort
      logger.warning("Timeout on loading page " + url);
      t.interrupt();
    }

This seems to work most of the time, however it might happen that the driver is really stuck and any subsequent call to driver will be blocked (I experience that with Chrome driver on Windows). Even something as innocuous as a driver.findElements() call could end up being blocked. Unfortunately I have no solutions for blocked drivers.

这似乎在大多数情况下都有效,但是可能会发生驱动程序真的被卡住并且对驱动程序的任何后续调用都将被阻止的情况(我在 Windows 上使用 Chrome 驱动程序时遇到过这种情况)。即使像 driver.findElements() 调用这样无害的事情也可能最终被阻止。不幸的是,我没有针对被阻止的驱动程序的解决方案。

回答by Lukasz

I had the same problem and thanks to this forum and some other found the answer. Initially I also thought of separate thread but it complicates the code a bit. So I tried to find an answer that aligns with my principle "elegance and simplicity".

我遇到了同样的问题,感谢这个论坛和其他一些人找到了答案。最初我也想到了单独的线程,但它使代码复杂化了一点。所以我试图找到一个符合我“优雅和简单”原则的答案。

Please have a look at such forum: https://sqa.stackexchange.com/questions/2606/what-is-seleniums-default-timeout-for-page-loading

请看看这样的论坛:https: //sqa.stackexchange.com/questions/2606/what-is-seleniums-default-timeout-for-page-loading

#

SOLUTION: In the code, before the line with 'get' method you can use for example:

解决方案:在代码中,在带有“get”方法的行之前,您可以使用例如:

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

One thing is that it throws timeoutException so you have to encapsulate it in the try catch block or wrap in some method.

一件事是它抛出 timeoutException ,因此您必须将其封装在 try catch 块中或包装在某些方法中。

I haven't found the getter for the pageLoadTimeout so I don't know what is the default value, but probably very high since my script was frozen for many hours and nothing moved forward.

我还没有找到 pageLoadTimeout 的 getter,所以我不知道默认值是什么,但可能非常高,因为我的脚本被冻结了好几个小时并且没有任何进展。

#

NOTICE: 'pageLoadTimeout' is NOT implemented for Chrome driver and thus causes exception. I saw by users comments that there are plans to make it.

注意:'pageLoadTimeout' 未为 Chrome 驱动程序实现,因此会导致异常。我从用户评论中看到,有计划做到这一点。

回答by sou

The solution of driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS)will work on the pages with synch loading. This does not solve, however, the problem on pages loading stuff in async, then the tests will fail all the time if we set the pageLoadTimeOut.

解决方案driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS)将适用于同步加载的页面。然而,这并不能解决页面异步加载内容的问题,如果我们设置了pageLoadTimeOut.

回答by premganz

I find that the timeout calls are not reliable enough in real life, particularly for internet explorer , however the following solutions may be of help:

我发现超时调用在现实生活中不够可靠,特别是对于 Internet Explorer,但是以下解决方案可能会有所帮助:

  1. You can timeout the complete test by using @Test(timeout=10000) in the junit test that you are running the selenium process from. This will free up the main thread for executing the other tests, instead of blocking up the whole show. However even this does not work at times.

  2. Anyway by timing out you do not intend to salvage the test case, because timing out even a single operation might leave the entire test sequence in inconsistent state. You might just want to proceed with the other testcases without blocking (or perhaps retry the same test again). In such a case a fool-proof method would be to write a poller that polls processes of Webdriver (eg. IEDriverServer.exe, Phantomjs.exe) running for more than say 10 min and kill them. An example could be found at Automatically identify (and kill) processes with long processing time

  1. 您可以通过在运行 selenium 进程的 junit 测试中使用 @Test(timeout=10000) 来使整个测试超时。这将释放主线程来执行其他测试,而不是阻塞整个节目。然而,即使这样有时也行不通。

  2. 无论如何,超时您并不打算挽救测试用例,因为即使是单个操作超时也可能使整个测试序列处于不一致状态。您可能只想在不阻塞的情况下继续执行其他测试用例(或者可能再次重试相同的测试)。在这种情况下,一个万无一失的方法是编写一个轮询器来轮询运行超过 10 分钟的 Webdriver(例如 IEDriverServer.exe、Phantomjs.exe)进程并杀死它们。可以在自动识别(和终止)处理时间长的进程中找到一个示例

回答by JasonYou

try

尝试

driver.executeScript("window.location.href='http://www.sina.com.cn'")

driver.executeScript("window.location.href='http://www.sina.com.cn'")

this statement will return immediately.

此语句将立即返回。

And after that , you can add a WebDriverWaitwith timeout to check if the page title or any element is ok.

之后,您可以添加一个带有超时的WebDriverWait来检查页面标题或任何元素是否正常。

Hope this will help you.

希望这会帮助你。

回答by flob

You can set the timeout on the HTTP Client like this

您可以像这样在 HTTP 客户端上设置超时

int connectionTimeout=5000;
int socketTimeout=15000;
ApacheHttpClient.Factory clientFactory = new ApacheHttpClient.Factory(new HttpClientFactory(connectionTimeout, socketTimeout));
HttpCommandExecutor executor =
      new HttpCommandExecutor(new HashMap<String, CommandInfo>(), new URL(seleniumServerUrl), clientFactory);
RemoteWebDriver driver = new RemoteWebDriver(executor, capabilities);

回答by Manjunath24

Used below code in similar situation

在类似情况下使用以下代码

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

and embedded driver.get code in a try catch, which solved the issue of loading pages which were taking more than 1 minute.

并在 try catch 中嵌入 driver.get 代码,解决了加载页面耗时超过 1 分钟的问题。