博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
学习直接调用Webdriver JsonWireProtocol 的 RESTful API
阅读量:6247 次
发布时间:2019-06-22

本文共 7215 字,大约阅读时间需要 24 分钟。

API 参考资料:

https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol

https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/webdriver-commands/

https://whitewaterhill.com/php-webdriver-bindings-0.9.0/status.html

 本文尝试直接使用Webdriver的REST API 去模拟Webdriver java binding 的实现,有利于更深入的了解Selenium Webdriver 和及其框架,在以后的项目中,如有需要修改框架,这也是最基本的知识,和甚至可以以自己的方式定制自己的binding,提供额外的功能。

 

 1. 启动selenium-server-standalone 作为REST api 服务

  • 启动hub:  java -jar selenium-server-standalone-2.53.0.jar -role hub
  • 启动node:   java -jar selenium-server-standalone-2.53.0.jar -role node -hub http://localhost:4444/grid/register -browser "browserName=firefox,firefx_binary=<PATH-TO-FIREFOX-EXECUTABLE>,maxInstances=6,platform=WINDOWS"

2. Hub和Node启动后,就可以发请求到相关服务API地址了,本例中hub和node都在本地启动

3. REST api 参照本文开头的链接,请求的链接格式 http://localhost:4444/wd/hub + <请求的api>

POST http://localhost:4444/wd/hub/session 就会返回创建好的session信息,以后所要的请求都是基于该session发生的。
package DriverJsonWirePro;import java.io.File;import java.io.FileOutputStream;import java.util.Base64;import java.util.Date;import java.util.Base64.Decoder;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.util.EntityUtils;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;public class CallRestFul {    static String hubUrl="http://localhost:4444/wd/hub";    static String sessionApi="/session";    static String deleteSessionApi="/session/:sessionId";    static String getUrlApi="/session/:sessionId/url";    static String findElementApi="/session/:sessionId/element";    static String clickElementApi="/session/:sessionId/element/:id/click";    static String sendKeysApi="/session/sessionId/element/:id/value";    static String takeScreenApi="/session/:sessionId/screenshot";    static HttpClient client = getHttpClient();    static String sessionId;            public static void main(String args[]) throws Exception{        sessionId=getSessionId("firefox");        try{        navigateUrl("www.google.com");        String elementId=findElementByCss(".mockClass.span #mockId");        sendKeys(elementId,"JsonWireProtocol");        elementId=findElementByCss(".mockClass #mockButon");        clickElement(elementId);        }catch(Throwable t){            //TODO        }finally {            deleteSession(sessionId);        }                }        public static String getSessionId(String browser) throws Exception{        String para="{\"desiredCapabilities\":{\"browserName\":\""+browser+"\"}}";        String url=hubUrl+sessionApi;        HttpPost post=postRequest(url, JSON.parseObject(para));        HttpResponse response = client.execute(post);        if(response.getStatusLine().getStatusCode()!=200) return null;                    String respStr=EntityUtils.toString(response.getEntity());        String sessionId=(String)JSON.parseObject(respStr).get("sessionId");        CallRestFul.sessionId=sessionId;        return sessionId;    }        public static HttpClient getHttpClient() {        HttpClient httpClient= HttpClientBuilder.create().build();        return httpClient;    }            public static boolean navigateUrl(String url) throws Exception {        String apiUrl=hubUrl+getUrlApi.replace(":sessionId", sessionId);        String para="{\"url\":\""+url+"\"}";        HttpPost post=postRequest(apiUrl, JSON.parseObject(para));        HttpResponse response=client.execute(post);        if(response.getStatusLine().getStatusCode()!=200) return false;        return true;    }        public static boolean deleteSession(String sessionId) throws Exception {        String apiUrl=hubUrl+deleteSessionApi.replace(":sessionId", sessionId);        HttpGet get=getRequest(apiUrl);        HttpResponse response = client.execute(get);        if(response.getStatusLine().getStatusCode()!=200) return false;        return true;    }        public static String findElementByCss(String cssSelector) throws Exception{        String para="{\"using\":\"css selector\","+"\"value\":\""+cssSelector+"\"}";        String apiUrl=hubUrl+findElementApi.replace(":sessionId", sessionId);        HttpPost post=postRequest(apiUrl, JSON.parseObject(para));        HttpResponse response = client.execute(post);        if(response.getStatusLine().getStatusCode()!=200) return null;                    String respStr=EntityUtils.toString(response.getEntity());        String elementId=(String)JSON.parseObject(respStr).getJSONObject("value").get("ELEMENT");        return elementId;    }        public static boolean clickElement(String elementId) throws Exception {        String apiUrl=hubUrl+clickElementApi                .replace(":sessionId", sessionId)                .replace(":id", elementId);        HttpPost post= postRequest(apiUrl,null);        HttpResponse response = client.execute(post);        if(response.getStatusLine().getStatusCode()!=200) return false;        return true;    }        public static boolean sendKeys(String elementId, String textToSend) throws Exception{        clickElement(elementId);        String para="{\"value\":[\""+textToSend+"\"]}";        String apiUrl=hubUrl+sendKeysApi                .replace(":sessionId", sessionId)                .replace(":id", elementId);        HttpPost post=postRequest(apiUrl, JSON.parseObject(para));        HttpResponse response = client.execute(post);        if(response.getStatusLine().getStatusCode()!=200) return false;        return true;    }        public static boolean takeScreenshot() throws Exception{            String apiUrl=hubUrl+takeScreenApi.replace(":sessionId", sessionId);        HttpPost post=postRequest(apiUrl, null);        HttpResponse response = client.execute(post);        if(response.getStatusLine().getStatusCode()!=200) return false;        JSONObject jsonObject=JSON.parseObject(EntityUtils.toString(response.getEntity()));        String srcreenInStr=(String)jsonObject.getString("value");        saveToLocal(srcreenInStr);        return true;    }        public static HttpPost postRequest(String url, JSONObject postJSON) {        HttpPost post= new HttpPost(url);        if(postJSON==null)             return post;                StringEntity sEntity;        try {            sEntity = new StringEntity(JSON.toJSONString(postJSON),"utf-8");            sEntity.setContentType("application/json");            post.setEntity(sEntity);        } catch (Throwable e){            e.printStackTrace();        }        return post;    }            public static HttpGet getRequest(String url) {        HttpGet get= new HttpGet(url);        return get;    }        public static boolean saveToLocal(String base64String) throws Exception {        Decoder decoder=Base64.getDecoder();        byte[] bytes=decoder.decode(base64String);                FileOutputStream fileOutputStream=new FileOutputStream(new File(".\\screenshot"+new Date().getTime()+".jpg"));        fileOutputStream.write(bytes, 0, bytes.length);        fileOutputStream.close();        return true;            }}

 

转载于:https://www.cnblogs.com/CUnote/p/5346460.html

你可能感兴趣的文章
给11gR2 RAC添加LISTENER监听器并静态注册
查看>>
IsAjaxRequest
查看>>
PHP中日期用到的字符
查看>>
ftpclient遍历目录文件,陷入死循环
查看>>
ERROR:column "rolcatupdate" does not exist
查看>>
js页面文字选中后分享到新浪微博实现
查看>>
StringUtils使用基本方法
查看>>
Linux常用命令大全
查看>>
开发自动化系列 工具集(三) 数据库开发工具
查看>>
阿里云-Xshell连接
查看>>
Android Studio 错误 Application Installation Failed...INSTALL_FAILED_INVALID_APK…
查看>>
操作系统--基本概念
查看>>
Redis中的跳跃表
查看>>
Query And Fetch & Query Then Fetch & DFS Query And Fetch & DFS Query Then Fetch
查看>>
搭建 Java Web 开发环境
查看>>
如何在Linux(CentOS 7)命令行模式安装VMware Tools
查看>>
记录下学习Go语言时用到的一些项目
查看>>
phonegap分享到微信插件(iOS版)
查看>>
Flex端使用alivepdf直接导出PDF文件:测试中文有乱码
查看>>
rabbitMQ、activeMQ、zeroMQ、Kafka、Redis 比较
查看>>