使用httpclient 調用selenium webdriver

結合上次研究的selenium webdriver potocol ,本身寫http request調用remote driver代替selenium APIhtml

selenium web driver Json protocol 相關請看 http://www.cnblogs.com/tobecrazy/p/5020741.htmljava

我這裏使用的是Gson 和 httpclientweb

首先,起一個remote severchrome

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

這裏要用到httpclient的Post 和delete methodapache

建立一個httpclient對象json

    HttpClient httpClient = HttpClients.createDefault();

建立一個post請求session

 

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

建立一個delete 請求app

     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();
		}

  

所有代碼以下:post

 

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,再好比須要作一些準備性工做,好比環境配置也能夠使用

相關文章
相關標籤/搜索