เราสามารถรอให้หน้าที่ซับซ้อนที่มี JavaScript โหลดด้วย Selenium หลังจากโหลดหน้าแล้ว เราสามารถเรียกใช้เมธอด Javascript document.readyState และรอจน เสร็จสมบูรณ์ ถูกส่งกลับ
ไวยากรณ์
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 to check page ready state
JavascriptExecutor j = (JavascriptExecutor)driver;
if (j.executeScript
("return document.readyState").toString().equals("complete")){
System.out.println("Page loaded properly.");
}
//expected condition presenceOfElementLocated
WebDriverWait wt = new WebDriverWait(driver,3);
try {
wt.until(ExpectedConditions
.presenceOfElementLocated
(By.id("gsc−i−id1")));
// identify element
driver.findElement
(By.id("gsc−i−id1")).sendKeys("Selenium");
}
catch(Exception e) {
System.out.println("Element not located");
}
driver.quit();
}
} ผลลัพธ์
