升级后Selenium调用Firefox webdriver报Host header不匹配错误如何解决
问题根因
该报错由geckodriver 0.29及以上版本新增的Host header安全校验机制触发。升级到Selenium 4.x后,原有直接修改全局DesiredCapabilities的代理配置方式存在兼容性问题,代理逻辑会干扰本地webdriver通信的Host头构造,而geckodriver默认仅接受Host值为localhost/127.0.0.1的本地请求,因此抛出校验失败错误。
解决方案
需对原有初始化代码做三处调整:
- 废弃直接修改全局
webdriver.DesiredCapabilities.FIREFOX的写法,将代理配置统一写入Options实例 - 使用Selenium 4.x推荐的
Service类指定geckodriver路径,替代已被标记为废弃的executable_path参数 - 给geckodriver添加
--allow-hosts启动参数,适配Host校验规则
修改后可运行的完整代码
from settings import PROXY_SETTINGS from selenium import webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.firefox.service import Service import traceback def initiate_driver(): try: myProxy = PROXY_SETTINGS # 清洗代理前缀(如果配置包含http/https协议头) myProxy = myProxy.replace("http://", "").replace("https://", "") proxy_ip, proxy_port = myProxy.split(":") options = Options() options.headless = True # 代理配置写入options options.set_preference("network.proxy.type", 1) options.set_preference("network.proxy.http", proxy_ip) options.set_preference("network.proxy.http_port", int(proxy_port)) options.set_preference("network.proxy.ssl", proxy_ip) options.set_preference("network.proxy.ssl_port", int(proxy_port)) options.set_preference("network.proxy.no_proxies_on", "") # 配置geckodriver服务,添加Host校验放行参数 service = Service( executable_path="/usr/local/bin/geckodriver", service_args=["--allow-hosts", "localhost"] ) driver = webdriver.Firefox(service=service, options=options) # driver.set_page_load_timeout(10) return driver except Exception as e: traceback.print_exc() print(e)
如果修改后仍存在报错,可以将service_args中的localhost替换为*,临时放开所有Host校验,确认是否为代理配置的其他规则导致的问题。
内容的提问来源于stack exchange,提问作者FoodCoderMan
相关产品推荐
相关产品推荐

