使用Python Selenium获取Performance Logs失败,代码报错求助
问题分析与解决方案
你的代码主要问题在于日志偏好设置方式错误,以及混淆了CDP Performance API和浏览器Performance Log的机制,以下是修正方案:
问题点拆解
- 直接通过
add_argument传递goog:loggingPrefs会因JSON转义问题导致配置失效,浏览器无法正确开启Performance Log收集。 - 调用
Performance.enableCDP命令是多余的,该命令用于获取性能指标数据,和driver.get_log("performance")依赖的日志系统不是同一机制。
修正后的代码
from selenium import webdriver import time from selenium.webdriver.chrome.service import Service options = webdriver.ChromeOptions() # 正确配置Performance Log偏好 options.set_capability("goog:loggingPrefs", {"performance": "ALL"}) options.add_argument("--auto-open-devtools-for-tabs") options.add_argument("--enable-logging") options.add_argument("--log-level=ALL") options.add_argument("--verbose") # options.add_argument("--headless") options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) driver = webdriver.Chrome(options=options) driver.get("https://gist.github.com/") # 等待页面加载完成,确保日志已生成 time.sleep(2) # 获取Performance Log performance_logs = driver.get_log("performance") print("可用日志类型:", driver.log_types) print("Performance Log条目数:", len(performance_logs)) time.sleep(10) driver.quit()
关键修改说明
- 正确配置日志偏好:使用
options.set_capability方法设置goog:loggingPrefs,避免手动转义JSON字符串带来的错误,确保浏览器正确开启Performance Log收集。 - 移除冗余CDP调用:删除
driver.execute_cdp_cmd("Performance.enable", {}),因为该命令和日志收集无关,反而可能造成不必要的资源占用。 - 增加加载等待:在
driver.get()后添加短暂等待,确保页面加载过程中生成足够的Performance Log条目,避免获取到空日志或因日志未生成导致的隐性错误。
内容的提问来源于stack exchange,提问作者Nub
相关产品推荐
相关产品推荐

