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

Selenium Python配置headless选项无效 浏览器窗口仍弹出问题求助

问题诱因
  • 核心原因:参数配置时机错误
    ChromeOptions的所有配置项必须在实例化webdriver.Chrome()之前完成设置。你的代码执行顺序是先创建了driver对象启动浏览器,之后才在函数内给options添加headless参数,此时修改的配置对已经启动的浏览器进程完全不生效,因此窗口还是会正常弹出。
  • 次要问题:参数写法不规范
    标准的headless启动参数需要带双横线前缀,即应该写为--headless,Chrome 112及之后的版本更推荐使用--headless=new(新版无头模式,功能和有界面模式完全一致,兼容性更好),你当前写的headless属于不规范写法,部分老版本Chrome可能无法识别。
修正后参考代码
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
PATH='C:\Coding_projects\chromedriver.exe'

# 先配置所有参数,再初始化driver
options = Options()
# 新版Chrome推荐用这个参数,兼容性更好
options.add_argument('--headless=new')
# 可选添加这个参数,避免部分场景下无头模式运行异常
options.add_argument('--disable-gpu')
driver=webdriver.Chrome(PATH,options=options)

def open_ouedkniss():
    driver.get("https://www.ouedkniss.com/")
    ad_button=driver.find_element_by_id('header_interstitiel_exit')
    ad_button.click()
    search_bar=driver.find_element_by_id('menu_recherche_query')
    search_bar.click()
    search_bar.send_keys('golf 6')
    search_bar.send_keys(Keys.RETURN)
    
open_ouedkniss()

补充说明:如果使用的是Selenium 4.0+版本,find_element_by_id方法已经被官方弃用,推荐替换为driver.find_element(By.ID, '元素id')的写法,使用前需要导入from selenium.webdriver.common.by import By。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:39:00