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

Selenium 4.10无法设置日志级别为ALL,无法读取完整网络日志

解决方案:undetected_chromedriver无法获取完整performance日志的问题

核心问题分析

你的推测方向正确:goog:loggingPrefs的配置未被undetected_chromedriver正确应用,导致日志级别始终为INFO,无法捕获完整网络请求日志。同时当前代码仅监听Network.responseReceived事件,遗漏了其他含URL的事件,固定sleep的等待方式也可能导致部分日志未被捕获。

修复步骤及代码调整

1. 正确传递日志偏好配置

undetected_chromedriver初始化时,需确保loggingPrefs被正确注入Chrome启动配置。可通过desired_capabilities参数直接传递,结合ChromeOptions的配置,保证版本兼容。

2. 提前启用Network域监控

在页面加载前,通过DevTools命令显式启用Network域,确保所有网络请求都被记录。

3. 替换固定sleep为显式等待

用Selenium显式等待替代固定sleep,等待页面关键元素加载完成,避免因时长不足丢失日志。

4. 监听更多Network事件

除Network.responseReceived外,Network.requestWillBeSent也包含请求URL,同时监听这两个事件可确保捕获所有请求。

修正后的完整代码

import json
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import undetected_chromedriver as uc
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

class Network:
    def __init__(self):
        opts = uc.ChromeOptions()
        opts.add_argument("--disable-blink-features=AutomationControlled")
        opts.add_argument("--ignore-certificate-errors")
        opts.add_argument(f"--user-agent=Lynx: Lynx/2.8.8pre.4 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/2.12.23")
        
        # 正确设置日志偏好,传递给desired_capabilities
        caps = opts.to_capabilities()
        caps['goog:loggingPrefs'] = {'performance': 'ALL'}
        
        self.driver = uc.Chrome(
            service=Service(ChromeDriverManager().install()),
            options=opts,
            desired_capabilities=caps
        )
        
        # 提前启用Network域监控
        self.driver.execute_cdp_cmd('Network.enable', {})

    def get_log(self):
        target_url = "你的目标URL"  # 替换为实际访问的URL
        self.driver.get(target_url)
        
        # 显式等待页面加载完成(示例:等待body元素出现)
        WebDriverWait(self.driver, 20).until(
            EC.presence_of_element_located((By.TAG_NAME, "body"))
        )
        
        # 获取并解析performance日志
        for log in self.driver.get_log("performance"):
            try:
                message = json.loads(log["message"])["message"]
                # 监听两种关键Network事件
                if message["method"] in ["Network.requestWillBeSent", "Network.responseReceived"]:
                    url = None
                    if message["method"] == "Network.requestWillBeSent":
                        url = message['params']['request']['url']
                    elif message["method"] == "Network.responseReceived":
                        url = message['params']['response']['url']
                    if url:
                        print(f"[{message['method']}] {url}")
            except Exception as e:
                # 忽略解析失败的日志
                continue
        
        self.driver.quit()

network = Network()
network.get_log()

额外注意事项

  • 确保undetected_chromedriver、ChromeDriver与本地Chrome浏览器版本匹配,版本不兼容会导致配置失效。
  • 部分网站会限制自动化工具的日志捕获,可尝试调整user-agent或添加反检测参数(如--disable-web-security、--no-sandbox等)。
  • 若日志仍不完整,可增加显式等待时长,或在页面交互后再次获取日志,避免遗漏异步加载的请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 21:20:06