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
相关产品推荐
相关产品推荐

