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

Python Selenium继承webdriver.Chrome时如何向super()传递扩展启动参数

问题根源

  • 第一版拆分代码的问题:调用super().__init__()时没有传递任何自定义参数,父类webdriver.Chrome使用默认配置初始化,因此你定义的扩展路径、启动参数都没有生效。
  • 第二次调整后的报错原因:Selenium不同版本的Chrome驱动构造函数的位置参数顺序存在差异,你直接按位置传入executable_path和options,会把Options对象误传给第一个位置的port参数,因此触发了「需要数字类型,得到Options类型」的报错。

解决方案

调用父类构造函数时明确指定参数名,不依赖位置顺序即可避免该问题,修正后的代码如下:

import variables as vb
from selenium import webdriver

class nokair(webdriver.Chrome):
    def __init__(self, executable_path = vb.driver_path, options = vb.chrome_options):
        self.driver_path = executable_path
        self.options = options
        # 明确指定参数名传递
        super().__init__(executable_path=executable_path, options=options)

init = nokair()

如果你使用的是Selenium 4及以上版本,executable_path参数已被官方弃用,更推荐用Service类管理驱动路径,写法更稳定:
首先调整variables.py:

from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

driver_path = r'C:/Users/path/to/chromedriver.exe'
extension_path = r'C:/Users/path/to/extension'

chrome_options = Options()
chrome_options.add_argument('load-extension=' + extension_path)
chrome_options.add_argument("--disable-notifications")
chrome_options.add_argument("--disable-infobars")

chrome_service = Service(executable_path=driver_path)

再调整类实现代码:

import variables as vb
from selenium import webdriver

class nokair(webdriver.Chrome):
    def __init__(self, service = vb.chrome_service, options = vb.chrome_options):
        self.service = service
        self.options = options
        super().__init__(service=service, options=options)

init = nokair()

内容的提问来源于stack exchange,提问作者Pete Kittinun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:39:03