Python Selenium同时使用--headless=new与user-data-dir时白窗口弹出问题
解决Chrome无头模式弹出白窗口的问题
关键参数调整
在Chrome选项中添加以下额外参数,强制抑制窗口显示并避免渲染异常:
--window-size=1x1:将窗口设置为极小尺寸,即使意外触发也完全不可见--disable-gpu:禁用GPU加速,消除无头模式下的渲染冲突--no-sandbox:关闭沙盒机制,解决部分环境下的窗口弹出问题--disable-extensions:禁用扩展,排除第三方扩展导致的窗口干扰
修改后的完整代码
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium import webdriver chrome_driver_path = r"C:\Program Files\chromedriver-win64\chromedriver.exe" # Update this path # Set up ChromeDriver service service = Service(chrome_driver_path) # Set up Chrome options to use the existing profile chrome_options = Options() chrome_options.add_argument("--headless=new") chrome_options.add_argument(r"user-data-dir=c:\Users\...\Default") # Path to your Chrome profile # 添加隐藏窗口的关键参数 chrome_options.add_argument("--window-size=1x1") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-extensions") # Initialize Selenium WebDriver with the same profile driver = webdriver.Chrome(service=service, options=chrome_options)
额外排查方向
如果上述参数无效,可尝试:
- 确认ChromeDriver与Chrome浏览器版本完全匹配(主版本号需一致,小版本差异可忽略)
- 清理目标用户配置文件中的异常启动设置(比如默认最大化窗口、固定窗口位置等)
- 替换为旧版无头模式参数
--headless=chrome,对比是否仍弹出窗口
内容的提问来源于stack exchange,提问作者yaqing wang
相关产品推荐
相关产品推荐

