结合上次研究的selenium webdriver potocol ,自己写http request调用remote driver代替selenium API

selenium web driver Json protocol 相关请看 http://www.cnblogs.com/tobecrazy/p/5020741.html

我这里使用的是Gson 和 httpclient

首先,起一个remote sever

 java -Dwebdriver.ie.driver="IEDriverServer.exe"   -Dwebdriver.chrome.driver="chromedriver.exe"  -jar selenium-server-standalone-2.48.0.jar

这里要用到httpclient的Post 和delete method

创建一个httpclient对象

    HttpClient httpClient = HttpClients.createDefault();

创建一个post请求

    JsonObject setCapability = new JsonObject();
setCapability.addProperty("browserName","firefox");
JsonObject capability = new JsonObject();
capability.add("desiredCapabilities",setCapability);
HttpPost httpPost = new HttpPost(base);

创建一个delete 请求

     url = base + sessionId ;
HttpDelete httpDelete = new HttpDelete(url);

从respose 中获取session ID

HttpResponse response = httpClient.execute(httpPost);

		try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("Response content length: "
+ entity.getContentLength()); String resultEntity = EntityUtils.toString(entity);
System.out.println("Response content: " + resultEntity);
JsonObject result= new JsonParser().parse(resultEntity).getAsJsonObject();
JsonElement sessionIdJson = result.get("sessionId");
if(!sessionIdJson.isJsonNull())
sessionId =sessionIdJson.getAsString();
JsonElement valueJson = result.get("value"); if(!valueJson.isJsonNull())
{
JsonObject tm=valueJson.getAsJsonObject();
JsonElement elementIdJson = tm.get("ELEMENT");
if(elementIdJson!=null)
elementId=elementIdJson.getAsString(); } }
} finally {
((Closeable) response).close();
}

  

全部代码如下:

import java.io.Closeable;
import java.io.IOException;
import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser; public class webDriverJson {
private static String base = "http://127.0.0.1:4444/wd/hub/session/";
private static String elementId;
static String sessionId = ""; public static void main(String[] args) throws Exception, IOException { HttpClient httpClient = HttpClients.createDefault(); JsonObject setCapability = new JsonObject();
setCapability.addProperty("browserName","firefox");
JsonObject capability = new JsonObject();
capability.add("desiredCapabilities",setCapability);
HttpPost httpPost = new HttpPost(base);
//create session
postExecutor(httpClient, httpPost, capability); String url = base + sessionId + "/url";
httpPost = new HttpPost(url); JsonObject getUrl = new JsonObject();
getUrl.addProperty("url", "http://www.baidu.com"); postExecutor(httpClient, httpPost, getUrl); //find input box
url = base + sessionId + "/element";
httpPost = new HttpPost(url);
JsonObject findElement = new JsonObject();
findElement.addProperty("using", "id");
findElement.addProperty("value", "kw");
postExecutor(httpClient, httpPost, findElement); System.out.println(elementId); url = base + sessionId + "/element/"+elementId+"/value";
httpPost = new HttpPost(url);
JsonObject typeElement = new JsonObject(); String json = "{\"value\":[\"webdriver\"]}";
JsonParser jp = new JsonParser();
typeElement = (JsonObject) jp.parse(json); postExecutor(httpClient, httpPost, typeElement); //find search button url = base + sessionId + "/element";
httpPost = new HttpPost(url);
JsonObject findSearchButton = new JsonObject();
findSearchButton.addProperty("using", "id");
findSearchButton.addProperty("value", "su");
postExecutor(httpClient, httpPost, findSearchButton);
System.out.println(elementId); url = base + sessionId + "/element/"+elementId+"/click";
httpPost = new HttpPost(url);
postExecutor(httpClient, httpPost,null); //delete session
url = base + sessionId ;
HttpDelete httpDelete = new HttpDelete(url); deleteExecutor(httpClient, httpDelete); } /**
* @author Young
* @param httpClient
* @param httpPost
* @param jo
* @throws UnsupportedEncodingException
* @throws IOException
* @throws ClientProtocolException
*/
public static void postExecutor(HttpClient httpClient, HttpPost httpPost,
JsonObject jo) throws UnsupportedEncodingException, IOException,
ClientProtocolException {
if(jo!=null)
{
StringEntity input = new StringEntity(jo.toString());
input.setContentEncoding("UTF-8");
input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httpPost.setEntity(input);
} HttpResponse response = httpClient.execute(httpPost); try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("Response content length: "
+ entity.getContentLength()); String resultEntity = EntityUtils.toString(entity);
System.out.println("Response content: " + resultEntity);
JsonObject result= new JsonParser().parse(resultEntity).getAsJsonObject();
JsonElement sessionIdJson = result.get("sessionId");
if(!sessionIdJson.isJsonNull())
sessionId =sessionIdJson.getAsString();
JsonElement valueJson = result.get("value"); if(!valueJson.isJsonNull())
{
JsonObject tm=valueJson.getAsJsonObject();
JsonElement elementIdJson = tm.get("ELEMENT");
if(elementIdJson!=null)
elementId=elementIdJson.getAsString(); } }
} finally {
((Closeable) response).close();
}
} /**
* @author Young
* @param httpClient
* @param delete
* @throws UnsupportedEncodingException
* @throws IOException
* @throws ClientProtocolException
*/
public static void deleteExecutor(HttpClient httpClient, HttpDelete delete) throws UnsupportedEncodingException, IOException,
ClientProtocolException { HttpResponse response = httpClient.execute(delete); try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("Response content length: "
+ entity.getContentLength()); String resultEntity = EntityUtils.toString(entity);
System.out.println("Response content: " + resultEntity);
JsonObject result= new JsonParser().parse(resultEntity).getAsJsonObject();
JsonElement sessionIdJson = result.get("sessionId");
if(!sessionIdJson.isJsonNull())
sessionId =sessionIdJson.getAsString();
JsonElement valueJson = result.get("value"); if(!valueJson.isJsonNull())
{
JsonObject tm=valueJson.getAsJsonObject();
JsonElement elementIdJson = tm.get("ELEMENT");
if(elementIdJson!=null)
elementId=elementIdJson.getAsString(); } }
} finally {
((Closeable) response).close();
}
} }

运行效果:

了解selenium 原理究竟有什么意义?

大多数人都会使用selenium去做自动化,但是不是每个人都了解selenium的原理,如果能掌握selenium原理

可以改造selenium API,使用webdriver protocol去做一些能够完善自动化测试框架的事情。、

比如,也许你在selenium自动化过程中会遇到get打开页面打不开,为了保证你脚本的健壮性,这时候你可以加入一段httprequest去获取

response的的关键值判断,如果不是2开头的可以设置refresh,再比如需要做一些准备性工作,比如环境配置也可以使用

使用httpclient 调用selenium webdriver的更多相关文章

  1. 关于IIS权限问题(Selenium WebDriver调用出错记录)

    本地VS调试过程中用Selenium WebDriver打开FF浏览器可以正常工作,项目部署至IIS后请求调用浏览器一直提示超时,异常如下: 因为本地调试可以成功,首先排除组件版本问题和浏览器兼容问题 ...

  2. selenium webdriver 右键另存为下载文件(结合robot and autoIt)

    首先感谢Lakshay Sharma 大神的指导 最近一直在研究selenium webdriver右键菜单,发现selenium webdriver 无法操作浏览器右键菜单,如图 如果我想右键另存为 ...

  3. Selenium Webdriver java 积累一

    Selenium Webdriver 学习: http://jarvi.iteye.com/category/203994 https://github.com/easonhan007/webdriv ...

  4. Selenium的PO模式(Page Object Model)|(Selenium Webdriver For Python)

            研究Selenium + python 自动化测试有近两个月了,不能说非常熟练,起码对selenium自动化的执行有了深入的认识. 从最初无结构的代码,到类的使用,方法封装,从原始函数 ...

  5. Selenium webdriver 操作日历控件

    一般的日期控件都是input标签下弹出来的,如果使用webdriver 去设置日期, 1. 定位到该input 2. 使用sendKeys 方法 比如: 但是,有的日期控件是readonly的 比如1 ...

  6. Selenium WebDriver中一些鼠标和键盘事件的使用

    转自:http://www.ithov.com/linux/133271.shtml 在使用 Selenium WebDriver 做自动化测试的时候,会经常模拟鼠标和键盘的一些行为.比如使用鼠标单击 ...

  7. selenium webdriver (python) 第一版PDF

    前言 如果你是一位有python语言基础的同学,又想通过python+ selenium去实施自动化,那么你非常幸运的找到了这份文档,我也非常荣幸能为你的自动化学习之路带来一丝帮助. 其实,我在sel ...

  8. selenium webdriver (python) 第三版

    感谢 感谢购买第二版的同学,谢谢你们对本人劳动成果的支持!也正是你们时常问我还出不出第三版了,也是你们的鼓励,让我继续学习整理本文档. 感谢乙醇前辈,第二版的文档是放在他的淘宝网站上卖的,感谢他的帮忙 ...

  9. Selenium WebDriver + Python 环境配置

    1.   下载必要工具及安装包 1.1.[Python开发环境] 下载并安装Python 2.7.x版本(当前支持2.x版本,不要下载最新的3.X的版本因为python3并非完全兼容python2) ...

随机推荐

  1. 常用js归纳

    一.获取地址栏参数 /*根据name获取URL参数*/ function getQueryString(name) { var reg = new RegExp("(^|&)&quo ...

  2. 【bzoj1004】 HNOI2008—Cards

    http://www.lydsy.com/JudgeOnline/problem.php?id=1004 (题目链接) 题意 n张卡片,染成3种颜色,每种颜色只能染固定张数.给出一些洗牌方案,问染色方 ...

  3. 批量从jar包中提取pom.xml

    将非maven项目转换为maven项目,首要第一步就是提取原工程依赖jar里的pom.xml,拼成<dependency>节点 import java.io.File; import ja ...

  4. 无限制使用ppt转pdf功能

    https://smallpdf.com/cn是一个pdf处理网站,十分好用,可是非注册用户有很多限制,比如用两次ppt转pdf就要等待: 于是就想如何让服务器认为我没有用过这个功能呢,感觉应该是用c ...

  5. Linux 基础

    命令说明 $ type cmd # 获取命令类型 $ which cmd # 命令的位置 $ help cmd / cmd --help / man cmd # 获取命令帮助 $ whatis cmd ...

  6. Java开发环境搭建——Idea开发环境

    Idea版本选择由于公司使用JDK7,所以我选择安装Version 2016.1.4(手动安装试验出来的,最新版的2016.1.4启动时提示需要安装JDK8)下载 其实可以安装多个版本的JDK,然后指 ...

  7. SQL Server存储过程创建和修改

    create proc Get_Data( @Del_ID varchar(36))asselect * from Depts where DeptId=@Del_ID select * from D ...

  8. 【CVE-2016-10009】OpenSSH < 7.4 - agent Protocol Arbitrary Library Loading

    粗看了一下,发现这个漏洞还是比较鸡肋的.如果前提条件满足,该漏洞可以在ssh server执行任意指令.不过前提是:1.攻击者可以往受害者磁盘上写文件.

  9. wampserver与 thinkphp 安装

    1.下载安装wampserver 2.设置phpmyadmin用户密码(首次密码是空的,所以需要重新设置) 设置密码 1.安装成功后,通过 phpmyadmin 进入mysql,点击上面的 [用户] ...

  10. excel工具类

    excel工具类 import com.iport.framework.util.ValidateUtil; import org.apache.commons.lang3.StringUtils; ...