Chúng ta có thể chờ cho đến khi trang tải xong với Selenium WebDriver. Có khái niệm đồng bộ hóa (synchronization) trong Selenium mô tả implicit wait và explicit wait. Để chờ trang tải xong, chúng ta sẽ sử dụng khái niệm explicit wait.
Explicit wait được thiết kế sao cho nó phụ thuộc vào điều kiện mong đợi (expected condition) cho hành vi cụ thể của một phần tử. Để chờ trang tải xong, chúng ta sẽ sử dụng expected condition presence_of_element_located cho một phần tử cụ thể. Khi thời gian chờ hết hạn, lỗi timeout sẽ được ném ra.
Để triển khai các điều kiện explicit wait, chúng ta phải nhờ đến lớp WebDriverWait và ExpectedCondition. Hãy kiểm tra sự hiện diện của phần tử dưới đây trên trang và xác minh xem trang đã tải xong chưa.

Ví dụ
Triển khai code
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
# presence_of_element_located expected condition chờ 8 giây
try:
w = WebDriverWait(driver, 8)
w.until(EC.presence_of_element_located((By.TAG_NAME, "h1")))
print("Page load happened")
except TimeoutException:
print("Timeout happened no page load")
driver.close()
Output
