使用BeautifulSoup爬取ESPN NFL赛程时find.text返回空字符串问题
问题原因及解决办法
核心原因
- 动态内容未加载:ESPN的NFL计分板中,比赛时间等核心数据是通过JavaScript动态渲染生成的。
requests库仅能获取页面的初始静态HTML,无法加载JS异步生成的内容,导致你要抓取的时间元素根本不在返回的响应内容里。 - CSS类名失效:网站可能更新了样式类命名,你代码中使用的
ScoreCell__Time ScoreboardScoreCell__Time h9 clr-gray-03这类复合class可能已被修改,导致选择器无法匹配到目标元素。 - 反爬拦截:直接用
requests发起请求时,缺少浏览器标识头,容易被ESPN的反爬机制识别为非正常请求,返回的内容可能被篡改或缺失关键数据。
解决思路
- 使用动态渲染工具
用selenium或playwright模拟浏览器行为,等待页面完全加载JS内容后再抓取,这是最可靠的方案。示例代码(selenium):
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 初始化浏览器驱动(需提前对应浏览器下载驱动) driver = webdriver.Chrome() driver.get("https://www.espn.com/nfl/scoreboard") # 等待时间元素加载完成,超时时间10秒 wait = WebDriverWait(driver, 10) time_elements = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, "ScoreboardScoreCell__Time"))) for elem in time_elements: print(elem.text) driver.quit()
- 更新CSS选择器
打开浏览器开发者工具(F12),定位当前页面中比赛时间元素的实际class属性,替换代码中的选择器。比如简化为更精准的单一class匹配:
import requests from bs4 import BeautifulSoup headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" } r = requests.get("https://www.espn.com/nfl/scoreboard", headers=headers) soup = BeautifulSoup(r.content, "lxml") # 用当前有效的class选择器查找 for time_div in soup.find_all("div", class_="ScoreboardScoreCell__Time"): print(time_div.text.strip() if time_div.text else "无可用时间数据")
- 添加请求头模拟浏览器
如果坚持使用requests,需添加User-Agent等请求头,让请求更接近正常浏览器行为,降低被拦截的概率(但仍无法解决动态加载问题)。
内容的提问来源于stack exchange,提问作者earningjoker430
相关产品推荐
相关产品推荐

