基于Python的Selenium浏览器会话软重启方法问询
复用已打开的Selenium Chrome浏览器会话方法
直接复制driver的字符串表示(比如<selenium.webdriver.chrome.webdriver.WebDriver (session="xxx")>)是没用的——这只是对象的文本描述,不是实际的会话连接。要复用已打开的浏览器,有两种可靠方法:
方法1:通过远程调试端口连接(推荐)
这种方法只要Chrome浏览器保持打开,就能随时重新连接,还能保留用户登录状态(可选),完美解决从欢迎页进入目标页耗时的问题。
第一次启动浏览器时的代码修改
调整初始化逻辑,指定远程调试端口和可选的用户数据目录:
from selenium import webdriver from selenium.webdriver.chrome.options import Options import time from bs4 import BeautifulSoup import numpy as np import matplotlib.pyplot as plt # 配置Chrome启动选项 options = Options() # 指定远程调试端口,选一个未被占用的端口(比如9222) options.add_argument("--remote-debugging-port=9222") # 可选:设置用户数据目录,保存登录状态、Cookie等,避免重复走欢迎页流程 options.add_argument("--user-data-dir=C:\\ChromeSessionProfile") # 启动浏览器并进入目标页面 driver = webdriver.Chrome(executable_path="C:\chromedriver.exe", options=options) driver.get("https://my_example.com/welcome") # 后续你的爬取、绘图代码保持不变... # 注释掉driver.quit(),让浏览器保持打开 # driver.quit()
后续重新连接浏览器的代码
当需要再次运行代码时,直接通过调试端口连接已打开的浏览器,无需重新加载页面:
from selenium import webdriver from selenium.webdriver.chrome.options import Options import time from bs4 import BeautifulSoup import numpy as np import matplotlib.pyplot as plt # 配置连接选项,指向已打开的Chrome调试端口 options = Options() options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") # 连接到已打开的浏览器 driver = webdriver.Chrome(executable_path="C:\chromedriver.exe", options=options) # 直接执行后续爬取、绘图逻辑,跳过欢迎页步骤 my_name = ["nm25", "nm26", "nm27", "nm33", "nm38", "nm41", "nm45", ] data_points = 450 my_file = np.zeros((13, 7, data_points)) x = [] y = [] # 剩下的代码保持不变...
方法2:通过Session ID和Executor URL连接
这种方法需要记录第一次会话的关键参数,适合临时复用,但如果chromedriver进程意外终止,连接会失效。
第一次运行时记录参数
在第一次启动浏览器后,打印并保存以下两个参数:
# 第一次启动后执行,打印并保存这两个值 print("Executor URL:", driver.command_executor._url) print("Session ID:", driver.session_id)
后续重新连接的代码
使用保存的参数构建新的WebDriver对象:
from selenium.webdriver.remote.webdriver import WebDriver from selenium.webdriver.chrome.service import Service import time from bs4 import BeautifulSoup import numpy as np import matplotlib.pyplot as plt # 启动chromedriver服务 service = Service("C:\chromedriver.exe") service.start() # 替换成你之前保存的Executor URL和Session ID driver = WebDriver( command_executor="http://127.0.0.1:xxxx", # 示例:http://127.0.0.1:54321 desired_capabilities={}, session_id="1a636e51f3d40bd9b66996e3d52d945b" ) # 直接执行后续爬取、绘图逻辑...
注意事项
- 确保第一次启动的Chrome浏览器没有关闭,否则无法建立连接。
- 如果使用用户数据目录,路径不能包含空格,且要保证有读写权限。
- 两种方法中,远程调试端口的方式更稳定,推荐优先使用。
内容的提问来源于stack exchange,提问作者Doug Smith
相关产品推荐
相关产品推荐

