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

Selenium加载页面后Chrome浏览器自动退出问题求助

解决Selenium执行后Chrome自动退出的问题

你的代码里虽然注释了driver.quit(),但在Selenium 4.x版本中,当Python脚本执行完所有代码逻辑后,会自动销毁WebDriver实例,导致浏览器跟着关闭——这是新版本的默认行为,不是代码写错了。

下面是三种可行的修复方案:

方案1:添加定时等待

在代码末尾加入time.sleep(),让脚本暂停一段时间,浏览器就能保持打开状态:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
import time

driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

driver.get('https://www.adamchoi.co.uk/overs/detailed')

all_matches_button = driver.find_element(By.XPATH, "//label[@analytics-event='All matches']")
all_matches_button.click()

time.sleep(30)  # 暂停30秒,时长可自行调整
# driver.quit()

方案2:等待用户手动触发结束

用input()等待用户按下回车键,只有用户操作后脚本才会结束,浏览器才会关闭:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

driver.get('https://www.adamchoi.co.uk/overs/detailed')

all_matches_button = driver.find_element(By.XPATH, "//label[@analytics-event='All matches']")
all_matches_button.click()

input("按下回车键关闭浏览器...")
# driver.quit()

方案3:配置Chrome参数让浏览器常驻

通过ChromeOptions设置detach=True,让浏览器在脚本执行完毕后依然保持打开状态,无需额外等待:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)

driver = webdriver.Chrome(options=options, service=ChromeService(ChromeDriverManager().install()))

driver.get('https://www.adamchoi.co.uk/overs/detailed')

all_matches_button = driver.find_element(By.XPATH, "//label[@analytics-event='All matches']")
all_matches_button.click()

# driver.quit()

内容的提问来源于stack exchange,提问作者Moniruzzaman Monir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 15:32:12