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

使用Selenium Python提取Python官网Upcoming Events板块日期出错求解决

问题:提取Python官网Upcoming Events板块日期出错的原因与解决方法

问题描述

尝试提取https://www.python.org/页面中Upcoming Events板块的日期,编写了以下Selenium Python代码:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

chrome_driver_path = "C:\develoment\chromedriver.exe"
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
driver.get("https://www.python.org/")

silent = driver.find_elements(By.TAG_NAME, 'time')
silent2 = [x.text for x in silent]
print(silent2)

运行后输出结果为:

['2023-03-08', '2023-02-15', '2023-02-10', '2023-02-08', '2023-02-08', '2023-03-13', '2023-03-15', '2023-03-22', '2023-04-01', '2023-04-07']

但该结果并非仅Upcoming Events板块的日期,请问哪里操作出错了?

错误原因

你使用driver.find_elements(By.TAG_NAME, 'time')会抓取整个页面所有<time>标签的文本。Python官网首页除了Upcoming Events板块,其他区域(比如过往活动、新闻动态板块)也包含<time>标签,因此输出结果混入了无关的日期数据。

解决方法

需要先定位到Upcoming Events板块的专属容器,再在该容器的上下文范围内查找<time>标签,这样就能只获取目标板块的日期。

修正后的代码

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
driver.get("https://www.python.org/")

# 定位Upcoming Events板块的父容器
upcoming_container = driver.find_element(By.CLASS_NAME, 'upcoming-widget')
# 在容器内查找所有time标签
event_time_elements = upcoming_container.find_elements(By.TAG_NAME, 'time')
# 提取日期文本
upcoming_dates = [elem.text for elem in event_time_elements]

print(upcoming_dates)
driver.quit()

代码说明

  1. 先通过upcoming-widget类定位到Upcoming Events板块的专属容器,确保后续查找范围被限制在目标区域内。
  2. 调用容器的find_elements方法查找<time>标签,此时只会返回该板块内的日期元素,不会混入其他区域的数据。

内容的提问来源于stack exchange,提问作者Joaquín Ruiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:30:29