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

Python中如何通过类向Selenium Chrome驱动传递Options参数

解决方案

你只需要在自定义Browser类的初始化流程中提前配置好Chrome Options实例,调用父类构造方法时将配置对象作为参数传入即可,修改后的可运行代码如下:

import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

class Browser(webdriver.Chrome):
    def __init__(self, headless: bool = True):
        self.driver_path = r"path/to/executable/file"
        os.environ['PATH'] += os.pathsep + self.driver_path
        
        # 构建Chrome启动配置
        chrome_options = Options()
        if headless:
            chrome_options.add_argument('--headless')
            # 无头模式下建议补充这两个参数,规避Linux/容器环境的启动报错
            chrome_options.add_argument('--no-sandbox')
            chrome_options.add_argument('--disable-dev-shm-usage')
        
        # 调用父类构造传入配置:Selenium 4.x 版本参数名为options,3.x旧版本参数名为chrome_options
        super().__init__(options=chrome_options)

    def some_function(self):
        # 自定义方法逻辑
        pass

注意事项

  • 如果你使用的是Selenium 3.x旧版本,将父类初始化的入参从options=chrome_options替换为chrome_options=chrome_options即可
  • 你当前将驱动路径加入系统PATH环境变量的写法是有效的,Selenium会自动从环境变量路径中查找匹配的Chrome驱动,不需要额外传入executable_path参数
  • 初始化Browser实例时如果需要关闭无头模式,只要传入headless=False即可,灵活度更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 02:54:20