none em>、eager 或 normal ] 通过 DesiredCapabilities 类或 ChromeOptions 类的实例使用如下:
-
使用DesiredCapabilities类:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
public class myDemo
{
public static void main(String[] args) throws Exception
{
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
DesiredCapabilities dcap = new DesiredCapabilities();
dcap.setCapability("pageLoadStrategy", "normal");
FirefoxOptions opt = new FirefoxOptions();
opt.merge(dcap);
WebDriver driver = new FirefoxDriver(opt);
driver.get("https://www.google.com/");
System.out.println(driver.getTitle());
driver.quit();
}
}
-
使用 ChromeOptions 类:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.PageLoadStrategy;
public class myDemo
{
public static void main(String[] args) throws Exception
{
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
FirefoxOptions opt = new FirefoxOptions();
opt.setPageLoadStrategy(PageLoadStrategy.NORMAL);
WebDriver driver = new FirefoxDriver(opt);
driver.get("https://www.google.com/");
System.out.println(driver.getTitle());
driver.quit();
}
}
您可以在Page load strategy for Chrome driver (Updated till Selenium v3.12.0)找到详细讨论
现在将 PageLoadStrategy 设置为 NORMAL 并且您的代码试用都确保 Browser Client 具有(即 Web Browser em>) 已达到'document.readyState' 等于"complete"。一旦满足这个条件,Selenium 就会执行下一行代码。
您可以在Selenium IE WebDriver only works while debugging找到详细讨论
但是 Browser Client 达到 'document.readyState' 等于 "complete" 仍然不能保证所有 JavaScript 和 Ajax 调用完成。
要等待所有 JavaScript 和 Ajax 调用 完成,您可以编写如下函数:
public void WaitForAjax2Complete() throws InterruptedException
{
while (true)
{
if ((Boolean) ((JavascriptExecutor)driver).executeScript("return jQuery.active == 0")){
break;
}
Thread.sleep(100);
}
}
您可以在Wait for ajax request to complete - selenium webdriver找到详细讨论
现在,通过 PageLoadStrategy 和 "return jQuery.active == 0" 的上述两种方法看起来正在等待不确定的事件。因此,对于一个明确的等待,您可以将WebDriverWait 与ExpectedConditions 设置为titleContains() 方法相结合,这将确保页面标题(即网页)是可见并假设所有元素也是可见的,如下所示:
driver.get("https://www.google.com/");
new WebDriverWait(driver, 10).until(ExpectedConditions.titleContains("partial_title_of_application_under_test"));
System.out.println(driver.getTitle());
driver.quit();
现在,虽然 页面标题 可能与您的 应用程序标题 匹配,但您想要交互的所需元素尚未完成加载。因此,更精细的方法是诱导 WebDriverWait 与 ExpectedConditions 设置为 visibilityOfElementLocated() 方法的联合使用,这将使您的程序等待所需的元素可见,如下所示:
driver.get("https://www.google.com/");
WebElement ele = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("xpath_of_the_desired_element")));
System.out.println(ele.getText());
driver.quit();
参考文献
您可以在以下位置找到一些相关的详细讨论: