使用 Selenium 等待包含 JavaScript 的复杂页面加载。

software testingautomation testingselenium web driverjavascript

我们可以使用 Selenium 等待包含 JavaScript 的复杂页面加载。页面加载后,我们可以调用 Javascript 方法 document.readyState 并等待直到返回 complete

语法

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("return document.readyState").toString().equals("complete");

接下来,我们可以通过在同步中使用 显式等待 概念来验证页面是否已准备好执行任何操作。我们可以等待元素的预期条件 presenceOfElementLocated。我们将在 try catch 块内实现整个验证。

示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.JavascriptExecutor;
public class PageLoadWt{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      // Javascript Executor 检查页面就绪状态
      JavascriptExecutor j = (JavascriptExecutor)driver;
      if (j.executeScript
      ("return document.readyState").toString().equals("complete")){
         System.out.println("页面已正确加载。");
      }
      //预期条件 presenceOfElementLocated
      WebDriverWait wt = new WebDriverWait(driver,3);
      try {
           wt.until(ExpectedConditions
         .presenceOfElementLocated
         (By.id("gsc−i−id1")));
         // 识别元素
         driver.findElement
         (By.id("gsc−i−id1")).sendKeys("Selenium");
      }
      catch(Exception e) {
         System.out.println("Element not located");
      }
      driver.quit();
   }
}

输出


相关文章