How to Determine Page Load Completion in Selenium
Selenium provides various approaches to check if a web page has completely loaded, including:
Page Load Timeout Setting
Using the pageLoadTimeout() method, Selenium waits for the page load to complete within a specified timeout. However, this method may not be reliable in all cases.
Set Page Load Strategy to Normal
You can set the pageLoadStrategy to normal using the DesiredCapabilities or ChromeOptions class. This ensures that the browser waits for the document.readyState to become "complete" before executing the next line of code.
Waiting for JavaScript and Ajax Calls
To wait for all JavaScript and Ajax calls to complete, you can use a custom function that checks the jQuery.active property:
public void waitForAjax2Complete() throws InterruptedException { while (true) { if ((Boolean) ((JavascriptExecutor)driver).executeScript("return jQuery.active == 0")){ break; } Thread.sleep(100); } }
Using ExpectedConditions
You can use the ExpectedConditions class to wait for specific conditions to be met before proceeding, such as the page title containing a certain string:
new WebDriverWait(driver, 10).until(ExpectedConditions.titleContains("partial_title_of_application_under_test"));
Or visibility of a particular element:
WebElement ele = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("xpath_of_the_desired_element")));
Conclusion
While there is no generic function in Selenium to check if a page has completely loaded, the approaches described above provide effective solutions for different use cases. By considering the page load strategy, waiting for JavaScript and Ajax calls, or using ExpectedConditions, you can ensure that your tests are waiting for the appropriate conditions before proceeding.
The above is the detailed content of How to Reliably Determine Web Page Load Completion in Selenium?. For more information, please follow other related articles on the PHP Chinese website!