如何让 Selenium 识别出页面已加载?
我们可以让 Selenium 识别到页面已加载。我们可以设置隐式等待以实现此目的。它将使驱动程序在页面加载后等待一段时间才可获取元素。
语法
driver.manage().timeouts().implicitlyWait();
在页面加载后,我们还可以调用 Javascript 方法 document.readyState 并一直等到返回 complete 为止。
语法
JavascriptExecutor js = (JavascriptExecutor)driver;
js.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 Pageload{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://tutorialspoint.com/index.htm";
driver.get(url);
// wait of 12 seconds
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
// identify element, enter text
WebElement m=driver.findElement(By.id("gsc-i-id1"));
m.sendKeys("Selenium");
}
}实例
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 PagaLoadJS{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://tutorialspoint.com/index.htm";
driver.get(url);
// Javascript executor to return value
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("return document.readyState")
.toString().equals("complete");
// get the current URL
String s = driver.getCurrentUrl();
// checking condition if the URL is loaded
if (s.equals(url)) {
System.out.println("Page Loaded");
System.out.println("Current Url: " + s);
}
else {
System.out.println("Page did not load");
}
driver.quit();
}
}输出

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