Selenium 4.10.0中desired_capabilities弃用后如何开启Chrome性能日志
在Selenium 4.10.0中开启Chrome Performance Log监控网络流量
在Selenium 4.x版本中,desired_capabilities参数已被弃用,需通过ChromeOptions配置浏览器能力。以下是适配新版本的实现方案:
步骤1:配置ChromeOptions启用Performance Log
使用set_capability方法设置日志偏好,注意Chrome的能力参数需添加goog:前缀(遵循W3C规范):
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service # 初始化ChromeOptions opts = Options() # 启用performance日志 opts.set_capability("goog:loggingPrefs", {"performance": "ALL"}) # 可选:精细化配置日志捕获范围 opts.set_capability("goog:perfLoggingPrefs", { "enableNetwork": True, # 开启网络事件日志捕获 "enablePage": False, # 关闭页面性能日志(按需调整) "enableTimeline": False # 关闭时间线日志(按需调整) })
步骤2:初始化ChromeDriver实例
通过service和options参数启动浏览器:
# 配置ChromeDriver服务(替换为你的chromedriver实际路径) service = Service(executable_path="/path/to/chromedriver") # 启动Chrome浏览器 driver = webdriver.Chrome(service=service, options=opts)
步骤3:获取并解析Performance Log
日志的message字段为JSON字符串,需解析后才能读取具体网络事件:
# 获取performance日志 logs = driver.get_log("performance") # 解析并筛选网络请求相关日志 import json for log_entry in logs: msg_data = json.loads(log_entry["message"])["message"] # 仅保留Network类事件(如请求发送、响应接收等) if msg_data["method"].startswith("Network."): print(msg_data)
关键说明
- Selenium 4之后,Chrome私有能力参数必须添加
goog:前缀,因此原loggingPrefs需改为goog:loggingPrefs。 perfLoggingPrefs用于控制日志类型,可根据需求开启或关闭不同类别的性能日志,减少冗余数据。
内容的提问来源于stack exchange,提问作者jeri neal
相关产品推荐
相关产品推荐

