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

driver.quit()后如何重启浏览器?解决I/O操作关闭文件报错

问题解答

1. driver.quit()之后重启浏览器

driver.quit()会彻底终止浏览器进程并释放所有关联资源,要重启浏览器只需重新初始化一个新的WebDriver实例即可。示例代码:

from selenium import webdriver
import time

# 第一次启动浏览器
driver = webdriver.Chrome()
driver.get("http://google.com")
time.sleep(2)
driver.quit()  # 关闭浏览器

# 重启浏览器
driver = webdriver.Chrome()
driver.get("http://google.com")
time.sleep(2)
driver.quit()

2. 解决"I/O Operation on closed file"错误

你遇到的错误是因为第一个with块执行完毕后,chrome_service的文件句柄已经被关闭,第二个with块复用同一个service实例时就会触发I/O错误。有两种解决方式:

方式一:每个with块重新创建Service实例

每次初始化webdriver.Chrome时都生成新的Service对象,确保每个driver使用独立的服务实例:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time

with webdriver.Chrome(service=Service()) as driver:
    driver.get("http://google.com")
    time.sleep(2)

with webdriver.Chrome(service=Service()) as driver:
    driver.get("http://google.com")
    time.sleep(2)

方式二:手动管理Service生命周期

如果需要复用Service,不要用with语句自动管理driver,手动控制driver的启动和关闭,最后统一停止Service:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time

# 初始化Service并启动
chrome_service = Service()
chrome_service.start()

try:
    # 第一次创建driver
    driver = webdriver.Chrome(service=chrome_service)
    driver.get("http://google.com")
    time.sleep(2)
    driver.quit()  # 仅关闭driver,不停止Service

    # 第二次创建driver,复用Service
    driver = webdriver.Chrome(service=chrome_service)
    driver.get("http://google.com")
    time.sleep(2)
    driver.quit()
finally:
    # 所有操作完成后停止Service
    chrome_service.stop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:10:10