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

如何解决ChromeDriver打开Chrome页面后立即关闭问题(无需while循环)

问题描述

使用Selenium打开网站时,Chrome页面一打开就自动关闭。尝试通过实现__exit__方法并设置teardown=False(仅当teardown=True时才退出程序),但该方法无效。只有在land_first_page方法中添加while(True): pass死循环语句时,页面才能保持打开状态。需要找到不使用死循环的解决办法。

相关代码

无死循环版本(页面自动关闭)

import types
import typing
import booking.constants as const
import os
from selenium import webdriver 
from selenium.webdriver.chrome.options import Options

class Booking(webdriver.Chrome):
    def __init__(self, driver_path=r"/SeleniumDrivers/chromedriver_mac_arm64", teardown=False):
        self.driver_path = driver_path
        self.teardown = teardown
        #self.options = Options()
        #self.options.add_experimental_option('detach', True)
        os.environ['PATH'] += self.driver_path
        super(Booking, self).__init__()

    def __exit__(self, exc_type, exc_value, traceback):
        if self.teardown:
            self.quit()

    def land_first_page(self):
        self.get(const.BASE_URL)
        #while(True):
        #    pass

加死循环版本(页面保持打开)

import types
import typing
import booking.constants as const
import os
from selenium import webdriver 
from selenium.webdriver.chrome.options import Options

class Booking(webdriver.Chrome):
    def __init__(self, driver_path=r"/SeleniumDrivers/chromedriver_mac_arm64", teardown=False):
        self.driver_path = driver_path
        self.teardown = teardown
        #self.options = Options()
        #self.options.add_experimental_option('detach', True)
        os.environ['PATH'] += self.driver_path
        super(Booking, self).__init__()

    def __exit__(self, exc_type, exc_value, traceback):
        if self.teardown:
            self.quit()

    def land_first_page(self):
        self.get(const.BASE_URL)
        while(True):
           pass
解决方案

以下是几种无需死循环即可保持Chrome页面打开的有效方法:

方法1:启用Chrome的detach实验性选项

该选项会让Chrome浏览器在WebDriver实例退出后保持打开状态,修改__init__方法如下:

def __init__(self, driver_path=r"/SeleniumDrivers/chromedriver_mac_arm64", teardown=False):
    self.driver_path = driver_path
    self.teardown = teardown
    self.options = Options()
    self.options.add_experimental_option('detach', True)  # 启用detach选项
    os.environ['PATH'] += self.driver_path
    super(Booking, self).__init__(options=self.options)  # 传入配置选项

方法2:正确使用上下文管理器(with语句)

__exit__方法只有在使用with语句创建对象时才会被触发执行。如果之前未使用with,对象销毁时会默认调用quit()导致页面关闭。调用代码示例:

with Booking(teardown=False) as bot:
    bot.land_first_page()
# 因teardown=False,__exit__不会调用quit(),页面保持打开

方法3:手动控制浏览器生命周期

如果不使用上下文管理器,确保不要主动调用quit()方法,或者在需要关闭浏览器时再执行该方法:

bot = Booking(teardown=False)
bot.land_first_page()
# 不调用bot.quit(),页面会保持打开;后续需要关闭时再执行bot.quit()

内容的提问来源于stack exchange,提问作者Vikram Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 12:48:10