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

Selenium类式开发中Chrome自动关闭及AttributeError报错求助

Selenium Chrome自动化问题解决

问题1:添加detach选项后Chrome仍自动关闭

原因分析

  • detach选项未正确绑定到ChromeOptions实例,或是driver实例在程序运行周期内被提前回收。
  • 代码中可能存在隐性的driver.quit()调用,或是Python解释器退出时触发了driver的销毁逻辑。

解决代码示例

确保在初始化ChromeOptions后正确添加选项,并将其传入driver构造:

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

class BookingBot:
    def __init__(self):
        # 初始化ChromeOptions并添加detach选项
        self.options = Options()
        self.options.add_experimental_option("detach", True)
        # 传入options创建driver实例
        self.driver = webdriver.Chrome(options=self.options)

    def start(self):
        self.driver.get("https://booking.com")
        # 执行你的自动化操作

# 确保实例在程序运行期间持续存在
if __name__ == "__main__":
    bot = BookingBot()
    bot.start()
    # 不要主动调用driver.quit(),除非你想手动关闭

问题2:继承webdriver.Chrome时出现AttributeError: 'dict' object has no attribute '_ignore_local_proxy'

原因分析

直接继承webdriver.Chrome时,未正确调用父类构造方法,或是参数传递错误(比如把Options实例传给了错误的参数位置,导致程序将其当作dict处理)。

解决代码示例

正确继承并调用父类构造,传递正确的options参数:

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

class BookingChrome(webdriver.Chrome):
    def __init__(self):
        # 初始化配置
        chrome_options = Options()
        chrome_options.add_experimental_option("detach", True)
        # 调用父类构造,明确传递options参数
        super().__init__(options=chrome_options)

    def run_automation(self):
        self.get("https://booking.com")
        # 自定义自动化逻辑

if __name__ == "__main__":
    driver = BookingChrome()
    driver.run_automation()

关键注意点

  • 继承webdriver.Chrome时,必须通过super().__init__()调用父类的构造方法,且参数要匹配父类定义。
  • 禁止直接将Options实例作为位置参数传递,必须指定options=关键字参数,否则会被当作executable_path参数处理,引发类型错误。

内容的提问来源于stack exchange,提问作者Syed Shahriar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 04:53:11