使用 Python 版 Selenium WebDriver 等待页面加载。
seleniumautomation testingtesting toolspython
我们可以使用 Selenium webdriver 等待页面加载。Selenium 中有一个 同步 概念,它描述了隐式和显式等待。要等待页面加载,我们将使用显式等待概念。
显式等待的设计使其依赖于元素特定行为的预期条件。要等待页面加载,我们将使用特定元素的预期条件 presence_of_element_loaded。等待时间一到,就会抛出超时错误。
要实现显式等待条件,我们必须借助 WebDriverWait 和 ExpectedCondition 类。让我们检查页面上是否存在以下元素,并验证页面是否已加载。
示例
代码实现
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 预期条件等待 8 秒 try: w = WebDriverWait(driver, 8) w.until(expected_conditions.presence_of_element_located((By.TA G_NAME,"h1"))) print("Page load happened") exception TimeException: print("Timeout happened no page load") driver.close()