Selenium Python WebDriver:如何消除‘DevTools listening...’提示
问题
环境:Python 3.11
使用以下代码配置ChromeOptions启动WebDriver:
chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("-incognito") chrome_options.add_argument("disable-infobars"); # disabling infobars chrome_options.add_argument("--disable-extensions"); # disabling extensions chrome_options.add_argument("--disable-gpu"); # applicable to windows os only chrome_options.add_argument("--disable-dev-shm-usage"); # overcome limited resource problems chrome_options.add_argument("--no-sandbox"); # Bypass OS security model chrome_options.add_argument(f"--headless={headless_option}") chrome_options.add_argument("--disable-logging") chrome_options.add_argument("--disable-crash-reporter") chrome_options.add_argument("--disable-in-process-stack-traces") service = Service(executable_path=executable_path) driver = webdriver.Chrome(service=service, options=chrome_options) url = r'https://www.google.com' driver.get(url) driver.quit()
尝试多种配置选项无效后,查看Selenium包中site-packages\selenium\webdriver\common\service.py文件的代码:
self.process = subprocess.Popen( cmd, env=self.env, close_fds=close_file_descriptors, stdout=cast(typing.Optional[typing.Union[int, typing.IO[typing.Any]]], self.log_output), stderr=cast(typing.Optional[typing.Union[int, typing.IO[typing.Any]]], self.log_output), stdin=PIPE, creationflags=self.creation_flags, startupinfo=start_info, **self.popen_kw, )
推测问题提示信息来自creationflags参数,寻求解决方法。
解决方案
方法1:通过Service的popen_kw参数覆盖配置
初始化Service时,传入popen_kw指定自定义的creationflags,强制设置为0(恢复默认进程创建行为):
service = Service(executable_path=executable_path) # 覆盖creationflags参数 service.popen_kw['creationflags'] = 0 driver = webdriver.Chrome(service=service, options=chrome_options)
方法2:直接修改Service实例的creation_flags属性
如果方法1无效,直接修改Service的creation_flags属性:
service = Service(executable_path=executable_path) service.creation_flags = 0 driver = webdriver.Chrome(service=service, options=chrome_options)
方法3:Windows系统专属配置
若运行环境为Windows,可配合startupinfo配置进一步调整:
import subprocess service = Service(executable_path=executable_path) startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW service.startupinfo = startupinfo service.creation_flags = 0 driver = webdriver.Chrome(service=service, options=chrome_options)
补充说明
creationflags是Windows系统下subprocess.Popen的专属参数,用于定义进程创建的特殊标志。Selenium默认可能设置了如CREATE_NO_WINDOW等标志,导致进程启动时出现异常提示或行为异常。设置creationflags=0会取消这些特殊标志,恢复系统默认的进程创建逻辑,大概率能解决相关问题。
内容的提问来源于stack exchange,提问作者user5023028
相关产品推荐
相关产品推荐

