You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Selenium显式等待直到网页加载出有效文本

Selenium显式等待页面加载完成的最简实现

核心思路

通过自定义显式等待条件,组合三类判断逻辑,满足任一条件即停止等待:

  • 页面标题非空且不含「加载/等待」类文本
  • 存在非空的meta description或keywords标签
  • 页面body包含非「加载/等待」类的有效文本

完整代码

import undetected_chromedriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By


options = Options()
options.add_argument('--ignore-ssl-errors=yes')
options.add_argument('--ignore-certificate-errors')
options.add_argument('--incognito')
options.add_argument('--headless')

driver = undetected_chromedriver.Chrome(service=Service(ChromeDriverManager().install()), 
                            use_subprocess=True,
                            options=options)

# 设置显式等待超时时间(可根据需求调整)
timeout = 10
wait = WebDriverWait(driver, timeout)

web_link = "amazon.com"
driver.get(f"http://{web_link}")

# 自定义等待条件,满足任一条件即结束等待
wait.until(lambda driver: 
    # 条件1:标题有效(非空且不含加载类文本)
    (driver.title.strip() != "" and not any(keyword in driver.title for keyword in ["加载", "等待", "Loading", "Waiting"]))
    or
    # 条件2:存在非空的meta描述或关键词标签
    (len(driver.find_elements(By.XPATH, '//meta[@name="description" and normalize-space(@content)!=""]')) > 0 
     or len(driver.find_elements(By.XPATH, '//meta[@name="keywords" and normalize-space(@content)!=""]')) > 0)
    or
    # 条件3:body包含有效文本(非空且不含加载类文本)
    (len(driver.find_element(By.TAG_NAME, "body").text.strip()) > 0 
     and not any(keyword in driver.find_element(By.TAG_NAME, "body").text for keyword in ["加载", "等待", "Loading", "Waiting"]))
)

# 此时页面已加载完成,可获取源码
page_html = driver.page_source
print(page_html)

# 记得关闭驱动
driver.quit()

代码说明

  1. 显式等待逻辑:使用lambda表达式自定义复合条件,通过WebDriverWait的until方法轮询判断,符合任一条件立即停止等待,避免无意义耗时。
  2. 多语言兼容:加入英文「Loading/Waiting」关键词,适配不同语言的加载提示。
  3. 元素判断:用find_elements而非find_element避免元素不存在时抛出异常,通过长度判断元素是否存在且符合要求。

内容的提问来源于stack exchange,提问作者Semzem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:35:01