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

如何通过Selenium在ChromeDriver中禁用页面自动刷新?

阻止ChromeDriver访问页面时自动刷新的解决方案

我太懂这种糟心的感觉了——刚要抓取网络日志,页面突然刷新回到初始状态,之前的准备全白费。针对你遇到的bet365页面自动刷新问题,这里有几个实用的解决思路,亲测有效:


方法1:用Chrome DevTools协议(CDP)直接拦截刷新

ChromeDriver支持调用CDP命令,我们可以从两个维度切断自动刷新的根源:

拦截刷新请求

在页面加载前注册网络拦截规则,把脚本触发的页面跳转/刷新请求直接掐掉:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
driver = webdriver.Chrome(options=options)

# 启用网络监控
driver.execute_cdp_cmd('Network.enable', {})

# 定义拦截逻辑:阻止脚本发起的文档跳转
def block_refresh(request):
    if request['type'] == 'Document' and request['initiator']['type'] == 'script':
        return {'cancel': True}
    return {'cancel': False}

# 开启请求拦截并绑定处理函数
driver.execute_cdp_cmd('Network.setRequestInterception', {'patterns': [{'urlPattern': '*'}]})
driver.add_event_listener('Network.requestIntercepted', block_refresh)

# 现在访问目标页面
driver.get("https://www.bet365.com/?lng=10&cb=10581211257#/IP/")

禁用页面定时器

很多网站的自动刷新是靠setInterval/setTimeout实现的,我们可以注入脚本直接废掉这些定时器:

# 页面加载后立刻执行脚本,清空定时器功能
disable_timer_script = """
// 覆盖定时器函数,让它们失效
window.setInterval = function() {};
window.setTimeout = function() {};
// 清除已存在的所有定时器
for(let i = 1; i < 99999; i++) {
    clearInterval(i);
    clearTimeout(i);
}
"""
driver.execute_script(disable_timer_script)

方法2:用Chrome扩展提前注入阻止逻辑

如果CDP的方式不够稳定,你可以做一个极简的Chrome扩展,在页面加载的最早期就植入阻止刷新的代码:

  1. 新建一个扩展文件夹,里面放两个文件:

    • manifest.json(扩展配置):
      {
        "manifest_version": 3,
        "name": "Block Page Refresh",
        "version": "1.0",
        "content_scripts": [
          {
            "matches": ["https://www.bet365.com/*"],
            "js": ["content.js"],
            "run_at": "document_start"
          }
        ]
      }
      
    • content.js(核心阻止脚本):
      // 阻止页面卸载(刷新/跳转)
      window.addEventListener('beforeunload', function(e) {
          e.preventDefault();
          e.returnValue = '';
      });
      // 废掉定时器
      window.setInterval = function() {};
      window.setTimeout = function() {};
      
  2. 在ChromeDriver中加载这个扩展:

    options.add_extension('path/to/your/extension_folder')
    driver = webdriver.Chrome(options=options)
    

方法3:移除页面中的刷新触发源

有些页面会用meta标签或者特定DOM元素触发刷新,我们可以直接把这些“隐患”删掉:

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, 10)
wait.until(EC.presence_of_element_located((By.TAG_NAME, 'body')))

# 移除页面中的自动刷新meta标签
driver.execute_script("""
const refreshMeta = document.querySelectorAll('meta[http-equiv="refresh"]');
refreshMeta.forEach(tag => tag.remove());
""")

⚠️ 小提醒:bet365这类网站有反爬机制,过于激进的拦截操作可能会触发检测,建议根据实际情况调整策略——比如不要一刀切拦截所有请求,只针对刷新相关的操作下手。

内容的提问来源于stack exchange,提问作者xingpei Pang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:21:15