昨天百度了半天关于Selenium Webdriver怎样重新使用已打开的浏览器的问题,就找到了这么位大佬的文章:

https://blog.csdn.net/wwwqjpcom/article/details/51232302

因为没积分,代码是在这下的

https://github.com/ANBUZHIDAO/myFirefoxDriver

把代码下下来研究了半天,勉强算是改了个Chrome版的,能够在已经打开的Chrome浏览器上继续操作,但是有很大缺陷,代码运行时不会报一些异常了,所以发出来希望有大佬帮忙修改一下,注解是我自己的理解,可能会有错

一共三个工具类,第一个是修改的ChromeDriver,代码如下

import static org.openqa.selenium.remote.CapabilityType.PROXY;import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ImmutableCapabilities;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.Command;
import org.openqa.selenium.remote.DriverCommand;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.Response;public class MyChromeDriver extends ChromeDriver {// 用于设置capabilitiesprivate Capabilities myCapabilities;public MyChromeDriver(String sessionID,String localserver) {mystartClient(localserver);mystartSession(sessionID);}//重写startSession方法,可以防止调用父级startSession方法而导致打开多个浏览器@Overrideprotected void startSession(Capabilities desiredCapabilities) {// Do Nothing}//改写的startClient方法,用于传入localserver(即浏览器的地址),配合sessionID能找出在用的浏览器protected void mystartClient(String localserver) {HttpCommandExecutor delegate = null;try {URL driverserver = new URL(localserver);delegate = new MyHttpCommandExecutor(driverserver);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();}setCommandExecutor(delegate);System.out.println("Connect to the existing browser");}//改写的startSession方法,用于传入sessionID,配合localserver能找出在用的浏览器protected void mystartSession(String sessionID) {if (!sessionID.isEmpty()) {super.setSessionId(sessionID);}Command command = new Command(super.getSessionId(), DriverCommand.STATUS);Response response;try {response = ((MyHttpCommandExecutor)getCommandExecutor()).execute(command);} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();System.out.println("Can't use this Session");return;}//打印系统信息System.out.println("response.getValue()" + response.getValue());if (response.getValue() instanceof Exception){((Exception)response.getValue()).printStackTrace();}//为了能执行Scriptthis.myCapabilities = dropCapabilities(new ChromeOptions()) ;}private static Capabilities dropCapabilities(Capabilities capabilities) {if (capabilities == null) {return new ImmutableCapabilities();}MutableCapabilities caps = new MutableCapabilities(capabilities);// Ensure that the proxy is in a state fit to be sent to the extensionProxy proxy = Proxy.extractFrom(capabilities);if (proxy != null) {caps.setCapability(PROXY, proxy);}return caps;
}@Overridepublic void quit() {try {execute(DriverCommand.QUIT);} catch (Exception e) {e.printStackTrace();}}public Capabilities getCapabilities() {return myCapabilities;}}

第二个修改的HttpCommandExecutor,应该是用来设置CommandCodec与ResponseCodec的,不大清楚

import static org.openqa.selenium.remote.DriverCommand.GET_ALL_SESSIONS;
import static org.openqa.selenium.remote.DriverCommand.NEW_SESSION;
import static org.openqa.selenium.remote.DriverCommand.QUIT;import java.io.IOException;
import java.net.URL;import org.openqa.selenium.NoSuchSessionException;
import org.openqa.selenium.SessionNotCreatedException;
import org.openqa.selenium.UnsupportedCommandException;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.remote.Command;
import org.openqa.selenium.remote.CommandCodec;
import org.openqa.selenium.remote.Dialect;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.HttpSessionId;
import org.openqa.selenium.remote.ProtocolHandshake;
import org.openqa.selenium.remote.Response;
import org.openqa.selenium.remote.ResponseCodec;
import org.openqa.selenium.remote.http.HttpClient;
import org.openqa.selenium.remote.http.HttpRequest;
import org.openqa.selenium.remote.http.HttpResponse;
import org.openqa.selenium.remote.http.W3CHttpCommandCodec;
import org.openqa.selenium.remote.http.W3CHttpResponseCodec;
import org.openqa.selenium.remote.internal.ApacheHttpClient;//该类是为了设置CommandCodec与ResponseCodec,父类这些默认为空
public class MyHttpCommandExecutor extends HttpCommandExecutor{private CommandCodec<HttpRequest> mycommandCodec;private ResponseCodec<HttpResponse> myresponseCodec;private final HttpClient myclient;public MyHttpCommandExecutor(URL addressOfRemoteServer) {super(addressOfRemoteServer);initCodec();this.myclient = new ApacheHttpClient.Factory().createClient(addressOfRemoteServer);}private void initCodec(){mycommandCodec = new W3CHttpCommandCodec();myresponseCodec = new W3CHttpResponseCodec();}@SuppressWarnings("deprecation")public Response execute(Command command) throws IOException {if (command.getSessionId() == null) {if (QUIT.equals(command.getName())) {return new Response();}if (!GET_ALL_SESSIONS.equals(command.getName()) && !NEW_SESSION.equals(command.getName())) {throw new NoSuchSessionException("Session ID is null. Using WebDriver after calling quit()?");}}if (NEW_SESSION.equals(command.getName())) {if (mycommandCodec != null) {throw new SessionNotCreatedException("Session already exists");}ProtocolHandshake handshake = new ProtocolHandshake();ProtocolHandshake.Result result = handshake.createSession(myclient, command);Dialect dialect = result.getDialect();mycommandCodec = dialect.getCommandCodec();myresponseCodec = dialect.getResponseCodec();return result.createResponse();}if (mycommandCodec == null || myresponseCodec == null) {throw new WebDriverException("No command or response codec has been defined. Unable to proceed");}HttpRequest httpRequest = mycommandCodec.encode(command);try {HttpResponse httpResponse = myclient.execute(httpRequest);Response response = myresponseCodec.decode(httpResponse);if (response.getSessionId() == null) {if (httpResponse.getTargetHost() != null) {response.setSessionId(HttpSessionId.getSessionId(httpResponse.getTargetHost()));} else {// Spam in the session id from the requestresponse.setSessionId(command.getSessionId().toString());}}if (QUIT.equals(command.getName())) {myclient.close();}return response;} catch (UnsupportedCommandException e) {if (e.getMessage() == null || "".equals(e.getMessage())) {throw new UnsupportedOperationException("No information from server. Command name was: " + command.getName(), e.getCause());}throw e;}
}
}

然后是个传参的类,水平太差,只能弄了个文件保存数据,希望有大佬能优化一下

package su.jian;import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;public class URLAndSession {public String getSessionID() throws IOException {FileReader fr = new FileReader("sessionID.txt");  BufferedReader br = new BufferedReader(fr);String sessionID = br.readLine();fr.close();return sessionID;}public void setSessionID(String sessionID) throws IOException {FileWriter fw = new FileWriter("sessionID.txt");fw.write(sessionID);fw.close();}public String getLocalserver() throws IOException {FileReader fr = new FileReader("localserver.txt"); BufferedReader br = new BufferedReader(fr);String localserver = br.readLine();fr.close();return localserver;}public void setLocalserver(String localserver) throws IOException {FileWriter fw = new FileWriter("localserver.txt");fw.write(localserver);fw.close();}}

最后是用例,能够在第一个打开的浏览器的同一个标签打开新网页,也可以定位元素,但是不会报异常

import java.io.IOException;
import java.util.concurrent.TimeUnit;import org.junit.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.HttpCommandExecutor;public class TestCase {private static URLAndSession uas = new URLAndSession();static {System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe");}public static void main(String[] args) throws IOException {//这儿没法用WebDriver定义,因为会没有getSessionId方法ChromeDriver driver = new ChromeDriver();//获取已打开浏览器的sessionIdString sessionId = driver.getSessionId().toString();System.out.println("sessionId:"+sessionId);//获取已打开浏览器的URLString url = ((HttpCommandExecutor)(driver.getCommandExecutor())).getAddressOfRemoteServer().toString();System.out.println(url);//保存数据uas.setSessionID(sessionId);uas.setLocalserver(url);driver.manage().window().maximize();driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);driver.get("http://www.baidu.com");}@Testpublic void testName() throws Exception {System.out.println(uas.getSessionID()+"==========="+uas.getLocalserver());//构造器获取sessionId和URLChromeDriver driver = new MyChromeDriver(uas.getSessionID(),uas.getLocalserver());driver.get("http://www.sohu.com/");}
}

望大佬修改,能给个现成的就更好了

Selenium Webdriver重新使用已打开的浏览器实例(Chrome版)相关推荐

  1. Selenium Webdriver重新使用已打开的浏览器实例

    本文转自:http://blog.csdn.net/wwwqjpcom/article/details/51232302 本文中的样例均使用SoapUI ,关于SoapUI+Webdriver 的配置 ...

  2. python控制已经打开的浏览器_使用python+selenium控制手工已打开的浏览器

    我们可以利用Chrome DevTools协议.它允许客户检查和调试Chrome浏览器. 打开cmd,在命令行中输入命令: chrome.exe --remote-debugging-port=922 ...

  3. selenium 如何在已打开的浏览器上直接自动化脚本

    selenium 如何在已打开的浏览器上继续运行自动化脚本? 前言: selenium测试网页每次登录都需要从头到尾登录到底,令人心烦: 此文章为直接在已打开.已登录/验证的网页运行提供方法: 一.配 ...

  4. python接管已经打开ie浏览器_使用selenium控制(接管)已打开的浏览器(chrome),并通过WebDriver值检测...

    在使用selenium进行自动化测试中我们有时会遇到这样的情况: 我们需要手动打开浏览器,进入到所需的页面,执行一些手动任务,如输入表单.输入验证码,登陆成功后,然后再开始运行自动化脚本. 这种情况下 ...

  5. 使用Selenium控制已打开的浏览器和网页

    使用Selenium控制已打开的浏览器和网页 之前遇到一个需求,就是需要登录某一个网站然后需要通过selenium从网页上自动获取一些信息:该网站需要通过手机验证码登录,通过selenium自动化登录 ...

  6. python selenium+firefox 使用已打开的火狐浏览器进行操作(不需要每次都重新打开火狐)

    使用selenium操作时,每次使用webdriver.Firefox()都要重新弹出火狐窗口,效率非常低,所以我一直在查,selenium能不能在已打开的浏览器上操作,发现该模块没有这个功能,那说明 ...

  7. selenium如何控制已打开浏览器

    在使用selenium进行Web自动化的时候,部分网站会有验证码.缓存等等原因,需在登录后再进行后续自动化.此时,就需控制在已打开的浏览器,在此,以 Chrome为例进行分析. 1.确定当前浏览器驱动 ...

  8. 如何利用 Selenium 对已打开的浏览器进行爬虫!

    大家好,我是安果! 在对某些网站进行爬虫时,如果该网站做了限制,必须完成登录才能展示数据,而且只能通过短信验证码才能登录 这时候,我们可以通过一个已经开启的浏览器完成登录,然后利用程序继续操作这个浏览 ...

  9. 如何利用 Selenium 对已打开的浏览器进行爬虫

    大家好! 在对某些网站进行爬虫时,如果该网站做了限制,必须完成登录才能展示数据,而且只能通过短信验证码才能登录 这时候,我们可以通过一个已经开启的浏览器完成登录,然后利用程序继续操作这个浏览器,即可以 ...

最新文章

  1. HotSpot模板解释器目标代码生成过程源码分析
  2. 20亿参数,大型视觉Transformer来了,刷新ImageNet Top1,All you need is money!
  3. Nginx服务测试时的一些配置:wireshark、常用搜索URL格式、关闭防火墙、siege
  4. 【MM】采购退货的处理办法
  5. 利用原生js做数据管理平台
  6. android随机崩溃莫名其妙,Android CrashHandler编写自己的异常捕获的方法
  7. android服务器连接失败,Android Studio服务器连接失败
  8. 如何在 Mac 上的“屏幕使用时间”中设置限定通信?
  9. 解决docker-compose: command not found
  10. 使用git checkout的方式进行轻量级部署
  11. MySql安装root用户密码设置失败问题解决
  12. java调用一个外部url_java 从程序内部调用外部url/接口
  13. FileLocator Pro:强大高效的无索引全文搜索软件
  14. 有哪些好用的低代码开发平台?
  15. 渠道为王:销售渠道建设3部曲 读后感
  16. [病毒分析]远程木马创建傀儡进程分析
  17. 世界五百强面试题计算机,世界五百强IT企业最新C++经典面试题及答案
  18. 谷歌浏览器提示adobeflashplayer已过期
  19. Cocoa Application-基础
  20. 工地反光衣穿戴检测算法

热门文章

  1. 前端三剑客之 HTML - JavaEE初阶 - 细节狂魔
  2. 微信小程序合成海报_微信小程序 canvas生成海报图片模糊问题
  3. 59岁“山寨机教母”,在天津造出市值191亿芯片公司,曾出走拖拉机研究所成就传奇...
  4. charge animation 充电管理u-boot(rk817)详解
  5. Java项目架构类型与项目分类
  6. 2019ICPC亚洲区域赛南昌网络赛
  7. 计算机专业英语基础知识,第一章 计算机专业英语基础知识
  8. 关于诺基亚S60 3rd自签名的全面理解
  9. H3C iNode智能客户端 破解
  10. Pacemaker+corosync实现高可用集群