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

如何在脚本执行后复用已打开的Chrome Driver窗口?

复用已启动的Chrome WebDriver实例

要实现跨脚本复用已打开的Chrome窗口(保留登录状态、页面进度),直接导入driver对象行不通——因为script1执行完毕后,Python进程结束,driver连接会断开。正确的做法是通过Chrome远程调试端口复用已运行的浏览器实例,步骤如下:

步骤1:在script1中启动带调试端口的Chrome实例

修改script1,配置ChromeOptions指定远程调试端口,启动后不要调用driver.quit(),让浏览器保持运行:

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

# 配置Chrome远程调试端口
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")

# 启动Chrome并连接到调试端口(端口未被占用时会启动新实例)
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://gmail.google.com/inbox/")

# 修正原代码的xpath引号嵌套问题
inbox_button = driver.find_element_by_xpath('//*[@id=":5a"]/div/div[2]/span/a')
inbox_button.click()

# 执行完操作后不要quit,保持浏览器打开
# driver.quit()  # 注释掉这行

步骤2:在script2中连接到已运行的Chrome实例

script2同样通过调试端口连接到已启动的Chrome,直接复用现有会话:

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

# 配置相同的调试端口,连接已运行的Chrome实例
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")

# 获取已有的driver实例
driver = webdriver.Chrome(options=chrome_options)

# 修正原代码语法错误:先定位所有邮件元素,再遍历操作
emails = driver.find_elements_by_xpath('path to emails')  # 替换为实际的xpath路径
print('找到的邮件数量:', len(emails))

for email in emails:
    email.click()  # 原代码误写为emails.click(),修正为单个邮件元素点击

注意事项

  • 确保端口9222未被其他程序占用,若被占用可更换为其他端口(如9223),两个脚本的端口需保持一致。
  • script1执行完毕后,Chrome浏览器必须保持打开状态,不能手动关闭。
  • 若需手动启动Chrome(而非通过script1启动),可在命令行执行:chrome.exe --remote-debugging-port=9222(Windows)或google-chrome --remote-debugging-port=9222(Linux/macOS),之后再运行脚本连接该端口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:55:32