Python Webdriver 重新使用已经打开的浏览器实例
因为Webdriver每次实例化都会新开一个全新的浏览器会话,在有些情况下需要复用之前打开未关闭的会话。比如爬虫,希望结束脚本时,让浏览器处于空闲状态。当脚本重新运行时,它将继续使用这个会话工作。还就是在做自动化测试时,前面做了一大推操作,但是由于程序出错,重启时不用再继续前面复杂的操作。
个人觉得这种功能非常有用,但是官方居然没有提供这种功能的API,苦苦搜搜,在网上找了两个java版的http://blog.csdn.net/wwwqjpcom/article/details/51232302 和 http://woxiangbo.iteye.com/blog/2372683
看了下源码其实java和python的驱动原理过程都非常相似。
打开一个Chrome会话:
from selenium import webdriver
driver = webdriver.Chrome()
运行上面的脚本,它将启动浏览器并退出。因为没有调用quit()方法,所以浏览器会话仍会存在。但是代码里创建的driver对象已经不在了,理论上不能用脚本控制这个浏览器。它将变成一个僵尸浏览器,只能手动杀死它。
通过webdriver启动一个浏览器会话大概会有这样三个阶段:
- 1、启动的浏览器驱动代理(hromedriver,Firefox的驱动程序,等等);
- 2、创建一个命令执行器。用来向代理发送操作命令;
- 3、使用代理建立一个新的浏览器会话,该代理将与浏览器进行通信。用
sessionId来标识会话。
因此只要拿到阶段2中的执行器和阶段3中的sessionID就能恢复上次的会话。这两个有api可以直接获取:
from selenium import webdriver
driver = webdriver.Chrome()
executor_url = driver.command_executor._url
session_id = driver.session_id
print(session_id)
print(executor_url)
driver.get("http://www.spiderpy.cn/")
得到类似这样的输出(第一个是会话的sessionId,第二个就是命令执行器连接):
397d725f042a076f7d4a82f7d3fead13
http://127.0.0.1:52869
一切就绪,下面就开始实现复用之前会话的功能,在Stack Overflow上面讲的实现是这样的:
from selenium import webdriver
driver = webdriver.Chrome()
executor_url = driver.command_executor._url
session_id = driver.session_id
driver.get("http://www.spiderpy.cn/")
print(session_id)
print(executor_url)
driver2 = webdriver.Remote(command_executor=executor_url, desired_capabilities={})
driver2.session_id = session_id
print(driver2.current_url)
可能是因为版本原因吧,反正在我环境中运行时,效果是实现了,能够重新连接到上一个会话,但是却打开了一个新的空白会话。看了下Remote类的源码,发现是因为每次实例化都会调用start_session这个方法新建一个会话。所以解决方法就是继承并重写这个类。自定义一个ReuseChrome这个类重写start_session方法使它不再新建session,使用传入的session_id:
from selenium.webdriver import Remote
from selenium.webdriver.chrome import options
from selenium.common.exceptions import InvalidArgumentException
class ReuseChrome(Remote):
def __init__(self, command_executor, session_id):
self.r_session_id = session_id
Remote.__init__(self, command_executor=command_executor, desired_capabilities={})
def start_session(self, capabilities, browser_profile=None):
"""
重写start_session方法
"""
if not isinstance(capabilities, dict):
raise InvalidArgumentException("Capabilities must be a dictionary")
if browser_profile:
if "moz:firefoxOptions" in capabilities:
capabilities["moz:firefoxOptions"]["profile"] = browser_profile.encoded
else:
capabilities.update({'firefox_profile': browser_profile.encoded})
self.capabilities = options.Options().to_capabilities()
self.session_id = self.r_session_id
self.w3c = False
然后在第二次连接是使用重写的ReuseChrome类:
from selenium import webdriver
# 第一次使用Chrome() 新建浏览器会话
driver = webdriver.Chrome()
# 记录 executor_url 和 session_id 以便复用session
executor_url = driver.command_executor._url
session_id = driver.session_id
# 访问百度
driver.get("http://www.spiderpy.cn/")
print(session_id)
print(executor_url)
# 假如driver对象不存在,但浏览器未关闭
del driver
# 使用ReuseChrome()复用上次的session
driver2 = ReuseChrome(command_executor=executor_url, session_id=session_id)
# 打印current_url为百度的地址,说明复用成功
print(driver2.current_url)
driver2.get("https://www.baidu.com")
这样就能顺利连接到上次没关闭的浏览器会话。
文章地址: http://www.spiderpy.cn/blog/detail/36
Python Webdriver 重新使用已经打开的浏览器实例的更多相关文章
- python webdriver api-对启动的火狐浏览器添加配置
Webdriver启用的火狐不带插件,可以自已进行配置 先找到火狐的安装路径 C:\Program Files\Mozilla Firefox 步骤说明 在CMD中使用cd命令进入firefox.ex ...
- Python+Selenium基础篇-打开和关闭火狐浏览器
本节介绍如何初始化一个webdriver实例对象driver,然后打开和关闭firefox浏览器.要用selenium打开fiefox浏览器.首先需要去下载一个driver插件geckodriver. ...
- Python脚本控制的WebDriver 常用操作 <一> 启动浏览器
由于本人的学习定位是基于Selenium+WebDriver+Python+FireFox+Eclipse+Pydev, 所以我的笔记也只和这方面相关. 我打算先学习基于Python脚本WebDriv ...
- 使用python+selenium控制手工已打开的浏览器
我们可以利用Chrome DevTools协议.它允许客户检查和调试Chrome浏览器. 打开cmd,在命令行中输入命令: chrome.exe --remote-debugging-port=922 ...
- Python+Selenuim测试网站,只能打开Firefox浏览器却不能打开网页的解决方法
最开始我使用的Selenium版本为2.48,Firefox版本为37,自动化打开网站的时候,可以正常打开. 后来由于Firefox的自检测更新,版本更新为47,导致版本不兼容,自动化打开网站浏览器时 ...
- python webdriver启动IE浏览器
from selenium import webdriverfrom selenium.webdriver.common.desired_capabilities import DesiredCapa ...
- [Python爬虫] 之二:Selenium 调用IEDriverServer打开IE浏览器安装配置
无论是selenium2(WebDriver)还是selenium2Library,如果想要调用ie浏览器,均需以下步骤. 下载IEDriverServer.进入索引页,首先选择版本号,IEDrive ...
- 用Python+selenium打开IE浏览器和Chrome浏览器的问题
这几天在学Python+selenium自动化,对三大浏览器Firefox,Chrome和IE都做了尝试,也都分别下载了对应的webdriver,如:geckodriver.chromedriver. ...
- selenium+python自动化105 - selenium 如何在已打开的浏览器上继续运行自动化脚本?
前言 使用selenium 做web自动化的时候,经常会遇到这样一种需求,是否可以在已经打开的浏览器基础上继续运行自动化脚本? 这样前面的验证码登录可以手工点过去,后面页面使用脚本继续执行,这样可以解 ...
随机推荐
- latex添加eps文档
latex添加图像时,要将.eps文档放在当前文件夹中,然后使用: % For one-column wide figures use\begin{figure}\begin{center}% Use ...
- Spring Cloud与微服务构建:Spring Cloud简介
Spring Cloud简介 微服务因该具备的功能 微服务可以拆分为"微"和"服务"二字."微"即小的意思,那到底多小才算"微&q ...
- Visual Studio 2013中UML建模功能
1.新建项目-->模版-->建模项目 2.右键项目,添加新建项,, 3.自己摸索吧.
- 【BZOJ2989】数列(CDQ分治,扫描线)
[BZOJ2989]数列(CDQ分治) 题面 BZOJ 权.....权限题.. 题解 Description 给定一个长度为n的正整数数列a[i]. 定义2个位置的graze值为两者位置差与数值差的和 ...
- 【BZOJ2813】奇妙的Fibonacci
Description Fibonacci数列是这样一个数列: F1 = 1, F2 = 1, F3 = 2 . . . Fi = Fi-1 + Fi-2 (当 i >= 3) pty忽 ...
- (转)Tomcat version 7.0 only supports J2EE 1.2, 1.3, 1.4, and Java EE 5 and 6 Web mod
背景:在sts中导入web项目,却不能通过sts中的tomcat来加载该服务,并报出如下错误. “Tomcat version 7.0 only supports J2EE 1.2, 1.3, 1.4 ...
- 【树状数组】【P4113】[HEOI2012]采花
Description 给定一个长度为 \(n\) 的序列,有 \(m\) 次询问,每次询问一段区间,求区间中有多少个数出现次数超过 \(1\) 次 Limitation \(n,~m~\leq~2~ ...
- striding layers 是什么意思?
https://www.zhihu.com/question/66283266/answer/240344515 第一句 We adapted the VGG-16 network (Simonyan ...
- matlab --- plot画图
plot画的图形在上一个plot的figure中:hold on 添加图例:legend({'X','Y'}) 限制X轴Y轴的坐标范围:xlim([380 780]);ylim([0 2]) 或 ax ...
- Service Fabric Placement and Load Balancing
作者:潘罡 (Van Pan)@ Microsoft 什么是PLB (Placement and Load Balancing) 介绍FM的上文中,我们提到了PLB. 这个组件和FM协同工作,为FM提 ...