Requests及PhantomJS爬取AHL冰球网站无法获取完整HTML代码如何解决?
问题原因
- 目标站点的比赛数据通过JavaScript异步请求后端接口后才渲染到页面,requests仅能获取初始未完成渲染的静态HTML,自然找不到目标元素
- PhantomJS已停止维护多年,浏览器指纹特征非常明显,会被站点反爬策略识别,无法触发正常的页面数据渲染流程
解决方案
方案1:直接调用数据接口(更高效稳定)
你可以通过浏览器开发者工具抓包获取数据接口,直接请求接口拿到结构化JSON数据,无需解析HTML:
- 打开目标页面后按F12切换到「网络」面板,筛选「Fetch/XHR」类型请求
- 刷新页面后逐个查看请求响应,找到包含比赛队名、比分字段的接口
- 直接对该接口发起请求,拿到JSON后直接提取字段即可,请求头带上正常的user-agent和referer即可正常请求
方案2:使用新版无头Chrome+Selenium规避检测
替换已废弃的PhantomJS,使用新版Chrome的无头模式,加上反爬检测规避配置,同时增加等待时间确保页面渲染完成:
from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By url = "https://theahl.com/stats/daily-schedule/2021-2-7?league=4&season=68&division=-1" chrome_options = Options() # 启用新版无头模式,指纹和普通浏览器一致 chrome_options.add_argument("--headless=new") chrome_options.add_argument("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") # 规避自动化检测 chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) chrome_options.add_experimental_option("useAutomationExtension", False) driver = webdriver.Chrome(options=chrome_options) # 移除webdriver特征 driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { "source": "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})" }) driver.get(url) # 显式等待目标元素加载完成,最多等待10秒 WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CLASS_NAME, "ht-team-name")) ) html = driver.page_source soup = BeautifulSoup(html, 'html.parser') team_name = soup.find_all('div',{'class':'ht-team-name'}) team_score = soup.find_all('span',{'class':'ht-period-value ht-total'}) print(team_name) print(team_score) driver.quit()
内容的提问来源于stack exchange,提问作者Ethan
相关产品推荐
相关产品推荐

