selenium 获取请求状态码

package Linkgap.Demo1;
import java.util.Iterator;
import java.util.logging.Level;

import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;

public class TestResponseCode
{
	@Test
    public void demo1()
    {
        // simple page (without many resources so that the output is
        // easy to understand
        String url = "http://www.w3school.com.cn/tiy/t.asp?f=ajax_httprequest_js_1";

        DownloadPage(url);
    }

    private static void DownloadPage(String url)
    {
        ChromeDriver driver = null;

        try
        {
            ChromeOptions options = new ChromeOptions();
            // add whatever extensions you need
            // for example I needed one of adding proxy, and one for blocking
            // images
            // options.addExtensions(new File(file, "proxy.zip"));
            // options.addExtensions(new File("extensions",
            // "Block-image_v1.1.crx"));

            DesiredCapabilities cap = DesiredCapabilities.chrome();
            cap.setCapability(ChromeOptions.CAPABILITY, options);

            // set performance logger
            // this sends Network.enable to chromedriver
            LoggingPreferences logPrefs = new LoggingPreferences();
            logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
            cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
            System.setProperty("webdriver.chrome.driver", "E:\\seleniumwork1\\Test1\\actuate\\chromedriver.exe");
            driver = new ChromeDriver(cap);

            // navigate to the page
            System.out.println("Navigate to " + url);
            driver.navigate().to(url);

            // and capture the last recorded url (it may be a redirect, or the
            // original url)
            
            driver.switchTo().frame("i");
            WebElement element = driver.findElement(By.cssSelector("body > button"));
            element.click();
            
            String currentURL = driver.getCurrentUrl();
            System.out.println("currentURL="+currentURL);
            // then ask for all the performance logs from this request
            // one of them will contain the Network.responseReceived method
            // and we shall find the "last recorded url" response
            LogEntries logs = driver.manage().logs().get("performance");

            int status = -1;

            System.out.println("\nList of log entries:\n");
            Iterator iterator = logs.iterator();
            LogEntry lastRequest;
            String megUrl;
            String method=null;
           
            JSONObject response=null;
            do {
            	 lastRequest= iterator.next();
            	 JSONObject json = new JSONObject(lastRequest.getMessage());
            	 JSONObject  message = json.getJSONObject("message");
                  method =message.getString("method") ;
                  if (method != null
                          && "Network.responseReceived".equals(method))
                  {
                  JSONObject params = message.getJSONObject("params");

                  response = params.getJSONObject("response");
                  
                  	
                  }
                
                
            	 
            }while(iterator.hasNext());
            //最后的请求  适用ajax 或者post请求
            String messageUrl = response.getString("url");
            //状态
            status = response.getInt("status");
            System.out.println(
                    "---------- bingo !!!!!!!!!!!!!! returned response for "
                            + messageUrl + ": " + status);

            System.out.println(
                    "---------- bingo !!!!!!!!!!!!!! headers: "
                            + response.get("headers"));
            System.out.println("\nstatus code: " + status);
          
            
          
            
        }catch (Exception e) {
        	 e.printStackTrace();
		}finally {

            if (driver != null)
            {
                driver.quit();
            }
		}
		}
//该注释下方是获取当前URL的状态码
           /* for (Iterator it = logs.iterator(); it.hasNext();)
            {
                LogEntry entry = it.next();

                try
                {
                    JSONObject json = new JSONObject(entry.getMessage());

                    System.out.println(json.toString());

                    JSONObject message = json.getJSONObject("message");
                    String method = message.getString("method");

                    if (method != null
                            && "Network.responseReceived".equals(method))
                    {
                        JSONObject params = message.getJSONObject("params");

                        JSONObject response = params.getJSONObject("response");
                        String messageUrl = response.getString("url");
                        System.out.println("messageUrl="+messageUrl);
                        if (currentURL.equals(messageUrl))
                        {
                            status = response.getInt("status");

                            System.out.println(
                                    "---------- bingo !!!!!!!!!!!!!! returned response for "
                                            + messageUrl + ": " + status);

                            System.out.println(
                                    "---------- bingo !!!!!!!!!!!!!! headers: "
                                            + response.get("headers"));
                        }
                    }
                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            System.out.println("\nstatus code: " + status);
        } finally
        {
            if (driver != null)
            {
                driver.quit();
            }
        }*/
        
    
}

 

你可能感兴趣的:(selenium)