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

Python中如何禁用Selenium各类日志并隐藏浏览器弹出窗口

Selenium 禁用全部日志+隐藏浏览器窗口/弹窗配置方案

以下代码可完全解决你遇到的WDM日志、Selenium弃用警告、Chrome DevTools日志三类输出问题,同时隐藏浏览器窗口及各类弹窗:

import os
import warnings
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

# 关闭WebDriver Manager(WDM)所有日志输出
os.environ['WDM_LOG_LEVEL'] = '0'
os.environ['WDM_PRINT_FIRST_LINE'] = 'False'

# 过滤Python层面的弃用警告
warnings.filterwarnings("ignore", category=DeprecationWarning)

# 配置Chrome启动参数
chrome_options = webdriver.ChromeOptions()
# 隐藏浏览器主窗口(无头模式,不需要隐藏窗口可删除本行)
chrome_options.add_argument('--headless=new')
# 禁用各类浏览器弹窗:通知请求、默认浏览器提示、首次运行引导等
chrome_options.add_argument('--disable-notifications')
chrome_options.add_argument('--no-default-browser-check')
chrome_options.add_argument('--no-first-run')
# 禁用Chrome日志输出
chrome_options.add_argument('--log-level=3')
chrome_options.add_argument('--silent')
chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])

# 配置Service对象,符合Selenium 4+规范避免弃用警告,同时关闭Service日志
service = Service(ChromeDriverManager().install())
service.creation_flags = 134217728  # Windows系统专用,禁用启动驱动时的黑色cmd弹窗,非Windows系统可删除本行
service.log_path = os.devnull

# 初始化浏览器
browser = webdriver.Chrome(service=service, options=chrome_options)

各配置作用说明:

  • WDM日志关闭:通过设置WDM_LOG_LEVEL环境变量为0,完全屏蔽webdriver manager的所有控制台输出,WDM_PRINT_FIRST_LINE屏蔽开头的空行输出
  • 弃用警告解决:Selenium 4+要求使用Service对象传入驱动路径,替代原来直接传executable_path的写法,同时搭配warnings.filterwarnings过滤剩余的Python警告
  • Chrome日志关闭:--log-level=3设置Chrome仅输出致命错误,excludeSwitches移除默认的日志开关,完全屏蔽DevTools listening类的输出
  • 弹窗&窗口隐藏:--headless=new启用Chrome新无头模式,完全不显示浏览器主窗口;其余参数禁用通知请求、默认浏览器设置弹窗、首次运行引导弹窗等所有浏览器触发的弹窗;service.creation_flags参数仅Windows有效,禁用启动驱动时弹出的黑色cmd窗口

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:27:06