使用httpclient 调用selenium webdriver
结合上次研究的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的更多相关文章
- 关于IIS权限问题(Selenium WebDriver调用出错记录)
本地VS调试过程中用Selenium WebDriver打开FF浏览器可以正常工作,项目部署至IIS后请求调用浏览器一直提示超时,异常如下: 因为本地调试可以成功,首先排除组件版本问题和浏览器兼容问题 ...
- selenium webdriver 右键另存为下载文件(结合robot and autoIt)
首先感谢Lakshay Sharma 大神的指导 最近一直在研究selenium webdriver右键菜单,发现selenium webdriver 无法操作浏览器右键菜单,如图 如果我想右键另存为 ...
- Selenium Webdriver java 积累一
Selenium Webdriver 学习: http://jarvi.iteye.com/category/203994 https://github.com/easonhan007/webdriv ...
- Selenium的PO模式(Page Object Model)|(Selenium Webdriver For Python)
研究Selenium + python 自动化测试有近两个月了,不能说非常熟练,起码对selenium自动化的执行有了深入的认识. 从最初无结构的代码,到类的使用,方法封装,从原始函数 ...
- Selenium webdriver 操作日历控件
一般的日期控件都是input标签下弹出来的,如果使用webdriver 去设置日期, 1. 定位到该input 2. 使用sendKeys 方法 比如: 但是,有的日期控件是readonly的 比如1 ...
- Selenium WebDriver中一些鼠标和键盘事件的使用
转自:http://www.ithov.com/linux/133271.shtml 在使用 Selenium WebDriver 做自动化测试的时候,会经常模拟鼠标和键盘的一些行为.比如使用鼠标单击 ...
- selenium webdriver (python) 第一版PDF
前言 如果你是一位有python语言基础的同学,又想通过python+ selenium去实施自动化,那么你非常幸运的找到了这份文档,我也非常荣幸能为你的自动化学习之路带来一丝帮助. 其实,我在sel ...
- selenium webdriver (python) 第三版
感谢 感谢购买第二版的同学,谢谢你们对本人劳动成果的支持!也正是你们时常问我还出不出第三版了,也是你们的鼓励,让我继续学习整理本文档. 感谢乙醇前辈,第二版的文档是放在他的淘宝网站上卖的,感谢他的帮忙 ...
- Selenium WebDriver + Python 环境配置
1. 下载必要工具及安装包 1.1.[Python开发环境] 下载并安装Python 2.7.x版本(当前支持2.x版本,不要下载最新的3.X的版本因为python3并非完全兼容python2) ...
随机推荐
- SQL Server-5种常见的约束
引自:http://www.cnblogs.com/dekevin/p/4772235.html SQLServer 中有五种约束, Primary Key 约束. Foreign Key 约束. U ...
- json的场景应用与实战
首先 要感谢慕课网的老师 地址:http://www.imooc.com/learn/68 下面我来开始总结: 什么是json的这些我就不多说了 不懂百度 <?php function cre ...
- 推公式hdu2298
(0,0)点到(x,y)以v射箭 问 最小的角度 不能射到 -1 x=v*cos(a)*t; y=v*sin(a)*t-0.5*g*t*t; 消去t; y=x*tan(a)-0.5*g*x*x/(v* ...
- python基础补漏-06-内置模块
1> sys 模块 sys.argv 命令行参数List,第一个元素是程序本身路径 sys.exit(n) 退出程序,正常退出时exit(0) sys.version 获取Python解释程序的 ...
- java学习笔记之线程2wait和notifyAll
2.乐观锁和悲观锁 悲观锁(Pessimistic Lock), 顾名思义,就是很悲观,每次去拿数据的时候都认为别人会修改,所以每次在拿数据的时候都会上锁,这样别人想拿这个数据就会block直到它拿到 ...
- Brackets
按下Ctrl + E("编辑")或退出编辑.Brackets将搜索项目下所有CSS文件 Ctrl/Cmd + Alt + P 打开即时预览功能 alt + command + O目 ...
- django进阶
路由系统 简而言之,django的路由系统作用就是使views里面处理数据的函数与请求的url建立映射关系.使请求到来之后,根据urls.py里的关系条目,去查找到与请求对应的处理方法,从而返回给客户 ...
- Linux如何进行文件管理
Linux中的所有数据都被保存在文件中,所有的文件被分配到不同的目录.目录是一种类似于树的结构,称为文件系统.当你使用Linux时,大部分时间都会和文件打交道,通过本节可以了解基本的文件操作,如创建文 ...
- dict与list的in 操作的速度
今天刷一道题,计算一串数字中其中两个数字相加等于目标值的题目,且取其中最早的两个数字(最后一个数字的位置靠前). 如[1,25,32,4,3,6,9,5] targer:9 输出 [3,6] ...
- [Android]快捷键
小技巧,快捷键 快捷键创建资源: Windows下是 alt+enter; Mac下是Option+enter 创建构造函数,Get/Set:Command+N,Windows环境中Alt + Ins ...