学习直接调用Webdriver JsonWireProtocol 的 RESTful API

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值