如何用Python的Selenium WebDriver获取HTTP响应?遇性能日志报错求助
解决Selenium Chrome中"invalid argument: log type 'performance' not found"错误
这个错误是因为Chrome 75+版本默认启用了W3C WebDriver协议,原来通过DesiredCapabilities设置loggingPrefs的方式已经不再生效,需要改用新的配置方式来启用性能日志。
修改后的完整代码
from selenium import webdriver from selenium.webdriver.chrome.options import Options # 配置Chrome选项以启用性能日志 options = Options() # 启用网络和页面性能日志的捕获 options.add_experimental_option('perfLoggingPrefs', { 'enableNetwork': True, 'enablePage': True }) # 使用W3C标准的日志配置键 options.set_capability('goog:loggingPrefs', {'performance': 'ALL'}) # 初始化Chrome驱动 driver = webdriver.Chrome( executable_path="C:\\Users\\Admin\\PythonFiles\\chromedriver.exe", service_args=["--verbose", "--log-path=D:\\selenium.log"], options=options ) driver.get('https://www.atg.party') print(driver.title) # 获取并打印性能日志 performance_log = driver.get_log('performance') print("=== Performance Log Entries ===") for entry in performance_log: print(entry) # 关闭驱动 driver.quit()
错误原因详解
在Chrome 75之前,我们可以通过DesiredCapabilities.CHROME['loggingPrefs']来配置日志,但Chrome切换到W3C协议后,这个旧的键被替换为goog:loggingPrefs(这是Chrome对W3C标准的扩展键)。如果还是用旧的loggingPrefs,WebDriver会无法识别performance这个日志类型,从而抛出你遇到的错误。
额外注意事项
- 驱动版本匹配:确保你的
chromedriver版本和Chrome浏览器版本完全对应(比如Chrome 77.x就用chromedriver 77.x),版本不匹配也可能导致各类兼容性问题。 - 备选方案(不推荐):如果你暂时无法适配W3C协议,可以强制关闭它来使用旧的日志配置方式,只需在
Options中添加:
不过这只是临时方案,W3C是WebDriver的标准方向,建议优先适配新的配置方式。options.add_experimental_option('w3c', False)
内容的提问来源于stack exchange,提问作者Rupesh Malla
相关产品推荐
相关产品推荐

