The driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(20))
method sets the maximum amount of time the driver should wait for a page load to complete before timing out. This means that if a page takes longer than 20 seconds to load, the driver will throw a TimeoutException
and stop waiting for the page to load. However, this method does not close the browser automatically after 20 seconds, it only sets the page load timeout.
The driver.quit()
method is used to close the browser and end the WebDriver session. But the driver.quit()
method is not affected by the page load timeout and it will close the browser immediately after it is called, regardless of how long the page has been loading.
So, if you want to close the browser after 20 seconds, you need to use the Thread.sleep(20000)
method, which will pause the execution of the program for 20 seconds, before calling the driver.quit()
method.
You could use a combination of both methods, by setting the page load timeout and then waiting for 20 seconds before closing the browser.
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(20));
driver.get("https://www.google.com");
Thread.sleep(20000);
driver.quit();
Alternatively, you could use a Timer and TimerTask to close the browser after a specific time like this:
import java.util.Timer;
import java.util.TimerTask;
...
driver.get("https://www.google.com");
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
driver.quit();
timer.cancel();
}
}, 20000);