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

Selenium with Python无法捕获console.log等控制台日志问题

解决Selenium无法捕获Chrome浏览器console日志的问题

问题概述

使用Selenium遍历项目URL排查控制台异常时,driver.get_log('browser')仅能获取无关日志,但手动打开浏览器开发者工具能看到完整的console.log/error/warning内容。环境配置:Chrome 122.0.6261.129、chromedriver 122.0.6261.128、Selenium 4.18.1、Python 3.10。

解决方案

1. 修正类方法的语法错误

原代码中ChromeDriver类的__init__和_login方法缺少self参数,会导致运行报错,先修正:

class ChromeDriver():
    def __init__(self, login_url, user, passwd):  # 添加self参数
        self.login_url = login_url
        self.user = user
        self.passwd = passwd

    def __enter__(self):
        options = Options()
        options.set_capability('goog:loggingPrefs', {'browser': 'ALL'})
        from selenium import webdriver
        self.driver = webdriver.Chrome(options=options)
        self.driver.maximize_window()
        self._login()
        return self.driver

    def _login(self):  # 添加self参数
        # 实现登录逻辑(示例)
        self.driver.get(self.login_url)
        # 自行补充用户名密码输入、提交等操作
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.driver.quit()

2. 调整日志捕获时机

原代码页面未完全加载就获取日志,导致日志未全部输出。修改check_console_logs函数,确保等待页面加载完成、日志输出后再捕获:

def check_console_logs(driver, url):
    try:
        driver.get(url)

        # 等待页面完全加载(document.readyState为complete)
        WebDriverWait(driver, 15).until(
            lambda d: d.execute_script('return document.readyState') == 'complete'
        )
        
        if '404' in driver.title:
            print(f'打开{url}失败: 404 Not found')
            return

        # 延迟3-5秒等待控制台日志输出(可根据页面实际调整)
        time.sleep(4)
        
        # 获取日志并过滤出console相关内容
        logs = driver.get_log('browser')
        if logs:
            print(f"{url}的控制台日志:")
            for log_entry in logs:
                # 过滤console.log/error/warn相关日志
                if 'console-api' in log_entry['message']:
                    print(f"[{log_entry['level']}] {log_entry['message']}")
            print()

    except Exception as ex:
        print(f"访问{url}时出错: {ex}")

3. 额外注意事项

  • 确保chromedriver与Chrome浏览器版本完全一致(当前版本差1个小版本,建议更新匹配);
  • 若使用无头模式,需添加配置保证日志捕获:
    options.add_argument('--headless=new')
    options.add_argument('--disable-gpu')
    
  • 部分前端框架的日志会在页面交互后输出,需在对应操作后再执行日志捕获逻辑。

内容的提问来源于stack exchange,提问作者A. L

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 12:34:54