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

Selenium ChromeDriver加载页面时JS脚本未执行问题求助

问题解决:Selenium ChromeDriver无法加载含rocket-loader的页面

核心原因

页面的rocket-loader.min.js是Cloudflare的加载组件,它会检测访问来源是否为自动化工具,Selenium默认配置容易被识别,导致页面内容不渲染。同时你的代码存在几处逻辑错误,一起修正:

解决方案步骤

1. 配置ChromeOptions绕过检测

给ChromeDriver添加以下参数,模拟正常浏览器的行为:

  • 禁用自动化提示标志
  • 设置真实用户代理(可从你日常使用的浏览器中复制)
  • 关闭Blink引擎的自动化检测
  • 禁用自动化扩展

2. 修复代码中的逻辑错误

  • 循环内重复创建driver会浪费资源,应在循环外初始化、循环结束后统一关闭
  • URL拼接错误:你误用了str(date)(整个列表),实际应使用循环变量x
  • 用find_elements代替find_element获取多个链接元素,避免循环报错
  • 替换脆弱的绝对XPATH为相对定位,防止页面结构变化导致定位失效

修改后的完整代码

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
from selenium.webdriver.chrome.options import Options

date_list = ["2022-11-02","2022-10-26","2022-10-19","2022-10-05"]
html = []
base_url = 'https://lfstats.com/scorecards/nightly?gametype=social&centerID=10&leagueID=0&isComp=0&date='

# 配置Chrome选项,绕过Cloudflare检测
chrome_options = Options()
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_argument("--disable-extensions")
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_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)

# 初始化driver,循环内复用
driver = webdriver.Chrome(options=chrome_options)
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")

try:
    for date in date_list:
        target_url = base_url + date
        driver.get(target_url)
        
        # 显式等待链接元素加载完成,最多等20秒
        wait = WebDriverWait(driver, 20)
        links = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div[class*='scorecard-item'] a")))
        
        for link in links:
            href = link.get_attribute('href')
            if href:
                html.append(href)
                print(f"获取链接:{href}")
finally:
    driver.quit()  # 最后关闭driver

print("所有获取的链接:", html)

代码说明

  • --disable-blink-features=AutomationControlled:关闭Chrome的自动化检测标志
  • execute_script修改navigator.webdriver:进一步隐藏自动化特征
  • 显式等待presence_of_all_elements_located:等待所有目标链接加载完成,比time.sleep更高效可靠
  • CSS选择器div[class*='scorecard-item'] a:相对定位,比绝对XPATH更稳定

内容的提问来源于stack exchange,提问作者Joe Hick

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:50:23