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

求助:Selenium无法同时禁用日志并以无头模式运行Chrome浏览器

求助:Selenium无法同时禁用日志并以无头模式运行Chrome浏览器

大家好,我现在碰到一个Selenium的棘手问题,先贴一下我目前的代码:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
import sys  # 补充你代码里漏的sys导入,不然会报错

options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-logging"])

if not("-dhl" in sys.argv or "--disable-headless" in sys.argv):
    options.add_argument("--headless=new")

self.driver = webdriver.Chrome(
    service=Service(ChromeDriverManager().install()),
    options=options
)
driver.get("https://google.com")

现在的问题是这两个配置没法同时生效:当我用--disable-headless参数启动时,日志确实被关掉了,但浏览器是正常窗口模式;如果不加这个参数,浏览器会进入无头模式,但各种日志还是会跳出来。我已经试过好几种方法都没用:

  • 换成options.headless = True来设置无头模式
  • 通过logging模块把全局日志级别设为logging.CRITICAL
  • 调换两个配置代码的顺序,担心后面的设置覆盖了前面的

总之就是死活没法同时实现「禁用日志+无头模式运行」,有没有大佬能帮忙看看问题出在哪?


可能的解决方案

其实这个问题主要是Chrome无头模式下的日志输出逻辑和正常模式有差异,excludeSwitches的设置在无头模式下可能没覆盖到所有日志输出通道,你可以试试同时给Chrome浏览器和ChromeDriver Service都加上日志禁用的配置,调整后的代码如下:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
import sys
import logging

# 先把Python层面的日志拉到最高级别,避免无关日志输出
logging.basicConfig(level=logging.CRITICAL)

options = webdriver.ChromeOptions()
# 保留原有的excludeSwitches设置
options.add_experimental_option("excludeSwitches", ["enable-logging"])
# 新增Chrome层面的日志禁用参数,无头模式下也能生效
options.add_argument("--log-level=3")
options.add_argument("--disable-logging")

if not("-dhl" in sys.argv or "--disable-headless" in sys.argv):
    options.add_argument("--headless=new")

# 给ChromeDriver Service也配置日志丢弃,避免驱动本身输出日志
service = Service(ChromeDriverManager().install())
# Windows系统用'NUL',Linux/macOS换成'/dev/null'
service.log_path = 'NUL'

self.driver = webdriver.Chrome(service=service, options=options)
driver.get("https://google.com")

关键调整点说明

  • 新增--log-level=3和--disable-logging这两个Chrome启动参数,直接从浏览器内核层面限制日志输出,无头模式下同样有效
  • 给Service设置log_path为系统空设备,把ChromeDriver自身产生的日志也直接丢弃
  • 同时配置Python全局日志级别,确保不会有第三方库的日志漏出来

你可以试试这个版本,应该能同时满足无头模式运行和禁用日志的需求。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 06:54:49