学习直接调用Webdriver JsonWireProtocol 的 RESTful API

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了学习直接调用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;
        
    }
}

 

以上是关于学习直接调用Webdriver JsonWireProtocol 的 RESTful API的主要内容,如果未能解决你的问题,请参考以下文章

From  selenium  import  webdriver

WebDriver 浅析

Selenium WebDriver API 学习笔记:浏览器控制

利用webdriver, openpyxl标记邮件中的英语并导出到Excel表格中

Selenium调用javascript

什么是Selenium Webdriver中的显式等待与隐式等待?