1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Selenium Webdriver重新使用已打开的浏览器实例(Chrome版)

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

时间:2022-03-16 20:57:14

相关推荐

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

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

/wwwqjpcom/article/details/51232302

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

/ANBUZHIDAO/myFirefoxDriver

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

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

import static org.openqa.selenium.remote.CapabilityType.PROXY;import java.io.IOException;import .MalformedURLException;import .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.mand;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 .URL;import org.openqa.selenium.NoSuchSessionException;import org.openqa.selenium.SessionNotCreatedException;import org.openqa.selenium.UnsupportedCommandException;import org.openqa.selenium.WebDriverException;import org.openqa.mand;import org.openqa.mandCodec;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("");}@Testpublic void testName() throws Exception {System.out.println(uas.getSessionID()+"==========="+uas.getLocalserver());//构造器获取sessionId和URLChromeDriver driver = new MyChromeDriver(uas.getSessionID(),uas.getLocalserver());driver.get("/");}}

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。