爬取PrizePicks平台CS2数据时遇超时问题求助
修复PrizePicks爬虫等待元素超时的建议
从几个核心排查方向入手,逐个验证解决:
1. 确认元素选择器有效性
页面结构可能更新,别死磕.projection类名:
- 打开Chrome开发者工具(F12),在Elements面板用Ctrl+F搜索
.projection,确认元素是否存在。 - 如果找不到,改用更灵活的选择器,比如
div[class*="projection"](CSS)或者//div[contains(@class, "projection")](XPath)。 - 替换等待代码示例:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 30) projections = wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[contains(@class, "projection")]')))
2. 检查iframe嵌套情况
很多动态内容会放在iframe内,Selenium默认不会进入iframe上下文:
- 用开发者工具查看
.projection元素是否在某个<iframe>标签里。 - 如果是,先切换到iframe再等待元素:
# 定位目标iframe(可通过src、id或XPath匹配) iframe = wait.until(EC.presence_of_element_located((By.XPATH, '//iframe[contains(@src, "prizepicks")]'))) driver.switch_to.frame(iframe) # 等待.projection元素 projections = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, "projection"))) # 操作完成后切回主文档 driver.switch_to.default_content()
3. 优化undetected_chromedriver初始化配置
默认配置可能无法规避反爬,补充参数增强隐蔽性:
import undetected_chromedriver as uc options = uc.ChromeOptions() options.add_argument("--disable-blink-features=AutomationControlled") options.add_argument("--disable-extensions") options.add_argument("--incognito") options.add_argument("--start-maximized") options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) # 初始化driver时指定Chrome主版本(匹配你的本地Chrome版本) driver = uc.Chrome(options=options, version_main=118)
4. 模拟用户行为触发内容加载
PrizePicks内容可能需要切换分类或滚动才会加载:
- 先切换到CS2分类:
# 等待并点击CS2分类标签 cs2_tab = wait.until(EC.element_to_be_clickable((By.XPATH, '//div[text()="CS2"]'))) cs2_tab.click() # 滚动页面触发动态加载 driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") import time time.sleep(2) # 给页面加载留缓冲时间
5. 验证登录/Cloudflare状态
- 如果页面有Cloudflare验证,运行代码时不要最小化浏览器,undetected_chromedriver通常能自动完成验证,若卡住可手动触发一次。
- 部分内容需要登录才能查看,先模拟登录流程:定位账号密码输入框,输入后点击登录按钮。
6. 调整等待策略
改用visibility_of_all_elements_located确保元素可见(而非仅存在于DOM):
projections = wait.until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "projection")))
内容的提问来源于stack exchange,提问作者JaCory Davison
相关产品推荐
相关产品推荐

