如何让 Selenium 2.0 等待页面加载?
我们让 Selenium 等待页面加载。我们可以在 Selenium 中使用同步概念来等待页面加载。隐式等待是一种应用于元素的同步类型,用于等待特定时间。
语法
driver.manage().timeouts().implicitlyWait();
我们也可以调用 JavaScript 方法document.readyState,并等待它产生值complete。Selenium 使用executeScript方法执行 JavaScript 命令。
语法
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript("return document.readyState").toString().equals("complete");执行完此步骤后,我们应检查 URL 是否与我们要查找的 URL 类似。
示例
使用隐式等待的代码实现。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class PageloadImplWt{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
// wait for page load
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
driver.get("https://tutorialspoint.com/index.htm");
// identify element
WebElement n=driver.findElement(By.id("gsc−i−id1"));
n.sendKeys("Selenium");
driver.quit();
}
}示例
使用 Javascript Executor 的代码实现。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class PagaLoadWtJS{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//launch URL
driver.get("https://tutorialspoint.com/index.htm");
// Javascript executor
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return document.readyState")
.toString().equals("complete");
// obtain current URL
String str = driver.getCurrentUrl();
// checking condition if the URL is loaded
if (str.equals(u)) {
System.out.println("Page Loaded");
System.out.println("Current Url: " + str);
}
else {
System.out.println("Page did not load");
}
driver.quit();
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP