[java] How do I set the selenium webdriver get timeout?

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.

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.

This question is related to java selenium webdriver

The answer is


Try this:

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

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.


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):

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.


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.


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:

  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


try

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

this statement will return immediately.

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

Hope this will help you.


You can set the timeout on the HTTP Client like this

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);

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

#

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

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.

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.

#

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


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception?

Examples related to webdriver

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? ImportError: No module named 'selenium' how to use List<WebElement> webdriver How to get attribute of element from Selenium? Selenium Finding elements by class name in python Open web in new tab Selenium + Python When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly How can I start InternetExplorerDriver using Selenium WebDriver