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

Selenium二次运行后返回空值问题求助

Selenium爬取SkySports英超积分榜二次运行返回空结果的解决方法

问题原因

  • 网站反爬机制触发:首次请求未被识别为自动化工具,二次请求因操作模式固定被网站拦截,导致目标数据未正常加载。
  • 浏览器会话残留:首次运行后未清理浏览器会话,二次请求时缓存或状态异常,影响页面渲染和元素定位。

解决方案

  • 添加随机延迟模拟人类操作:在页面加载前后加入随机等待时间,避免请求频率过于规律被识别。
  • 自定义请求头:设置真实的User-Agent,避免Selenium默认标识被网站检测到。
  • 清理浏览器会话:每次运行结束后关闭浏览器,确保每次请求都是全新的实例。
  • 优化等待条件:等待数据区域的核心元素(如表格行)加载完成,而非单个链接,确保数据完全渲染。

修改后的代码示例

from selenium import webdriver
from selenium.common import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import random
import time

# 配置Chrome选项,添加真实User-Agent
options = webdriver.ChromeOptions()
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")

browser = webdriver.Chrome(options=options)
browser.get('https://www.skysports.com/premier-league-table')

# 随机等待2-5秒,模拟人类浏览行为
time.sleep(random.uniform(2, 5))

# 处理Cookie同意弹窗(如果存在)
try:
    cookie_btn = WebDriverWait(browser, 5).until(
        EC.element_to_be_clickable((By.ID, 'onetrust-accept-btn-handler'))
    )
    cookie_btn.click()
except TimeoutException:
    print("无Cookie同意弹窗")

# 等待表格行元素加载完成
delay = 10
try:
    WebDriverWait(browser, delay).until(
        EC.presence_of_element_located((By.CLASS_NAME, 'standing-table__row'))
    )
    print("页面加载完成!")
except TimeoutException:
    print("页面加载超时!")

body = browser.find_element(By.XPATH, "//table[@class='standing-table__table']/tbody")
items = body.find_elements(By.CLASS_NAME, 'standing-table__row')
for item in items:
    name = item.find_element(By.CLASS_NAME, 'standing-table__cell--name-link')
    print(name.text)

# 关闭浏览器,清理会话
browser.quit()

内容的提问来源于stack exchange,提问作者Daniel Tobi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:32:41