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

Python Selenium下FirefoxWebElement如何提取子元素文本内容

Selenium提取排班字段问题解决方案

报错根因

  • Selenium 4+ 已废弃find_element_by_class_name系列旧API,直接调用会出现定位失败
  • 未添加等待逻辑,元素未完全渲染就执行查找操作
  • 部分appointment-template类div可能缺少对应字段,无异常捕获逻辑
  • 现有代码仅打印WebElement对象,未提取文本属性,即使定位成功也拿不到目标值

修复后完整代码

首先导入必要依赖:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException

替换原有查找和提取逻辑:

# 先等待所有排班div加载完成,最长等待10秒
wait = WebDriverWait(driver, 10)
divs = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'appointment-template')))

for div in divs:
    try:
        # 提取排班标题
        title = div.find_element(By.CLASS_NAME, 'title').text.strip()
        # 提取完整时间
        time_val = div.find_element(By.CLASS_NAME, 'time').text.strip()
        # 提取讲师姓名
        teacher = div.find_element(By.CSS_SELECTOR, 'ul.docent li').text.strip()
        # 输出结果
        print(title)
        print(time_val)
        print(teacher)
        print("-"*30)
    except NoSuchElementException:
        # 跳过缺少对应字段的异常排班div
        continue

补充说明

如果仍偶发定位失败,可替换为相对XPATH定位,强制从当前div子节点查找,避免全局匹配干扰:
例:查找标题的写法改为 title = div.find_element(By.XPATH, './p[@class="title"]').text.strip()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 22:06:04