如何在终止Selenium Remote Webdriver脚本后关闭会话?
解决Selenium Remote WebDriver脚本终止时自动关闭会话的问题
核心解决思路
当你用Ctrl+C终止脚本时,系统会向进程发送SIGINT信号,Python会触发KeyboardInterrupt异常。我们可以通过捕获这个异常,或者注册信号处理函数,在脚本终止前强制调用driver.quit()来立即关闭Remote会话。
方案一:捕获KeyboardInterrupt异常
把业务逻辑包裹在try-except块中,在捕获到终止信号时主动关闭会话:
from selenium import webdriver # 初始化Remote WebDriver driver = webdriver.Remote( command_executor="你的个人端点URL", desired_capabilities={} # 替换为你的设备/浏览器配置 ) try: # 你的核心业务逻辑 driver.get("https://example.com") # ...其他操作 except KeyboardInterrupt: print("脚本被终止,正在关闭Remote会话...") driver.quit() finally: # 兜底处理:确保即使其他异常发生也尝试关闭会话 try: driver.quit() except Exception: pass
方案二:注册信号处理函数
用signal模块监听SIGINT信号,收到信号时直接执行会话关闭操作:
import signal from selenium import webdriver # 初始化Remote WebDriver driver = webdriver.Remote( command_executor="你的个人端点URL", desired_capabilities={} ) def handle_termination(signum, frame): print("收到终止信号,立即关闭Remote会话...") driver.quit() exit(0) # 绑定SIGINT信号的处理函数 signal.signal(signal.SIGINT, handle_termination) # 执行业务逻辑 try: driver.get("https://example.com") # ...如果是长运行脚本,比如循环等待操作 while True: pass except Exception as e: print(f"脚本运行出错: {str(e)}") driver.quit()
注意事项
- 确保
driver对象在异常块或信号处理函数中处于可访问的作用域。 - 如果脚本涉及多线程,需要注意线程安全,避免重复调用
driver.quit()。 - 测试时可以手动触发Ctrl+C,检查Remote端点的会话是否被立即销毁,而非等待30分钟超时。
内容的提问来源于stack exchange,提问作者Takamura
相关产品推荐
相关产品推荐

