45

How to get the HTTP status code in Selenium?

E.g. so I can test that if the browser requests /user/27 and no user with ID=27 exists, an HTTP 404 is returned?

My primary interest is Selenium RC, but if someone knows the answer for "normal" selenium, I can probably easily translate it into RC.

/Pete

Ripon Al Wasim
  • 34,088
  • 37
  • 146
  • 165
Pete
  • 11,727
  • 8
  • 47
  • 63
  • Possible duplicate of [Checking HttpResponse OK (200) with Selenium WebDriver](http://stackoverflow.com/questions/14537336/checking-httpresponse-ok-200-with-selenium-webdriver) – Kzqai Jan 14 '16 at 17:57
  • 2
    This question is not exactly a duplicate, because when I asked the question 6 years ago, I was talking about Selenium RC which predates WebDriver. But that also makes this question rather irrelevant because I don't think people would use the old API anymore. – Pete Jan 15 '16 at 09:07

7 Answers7

10

This might not be the best use of Selenium for this type of test. There is unnecessary need to load a browser when you could do and have a faster running test

[Test]
[ExpectedException(typeof(WebException), UserMessage = "The remote server returned an error: (404) Not Found")]
public void ShouldThrowA404()
{
    HttpWebRequest task; //For Calling the page
    HttpWebResponse taskresponse = null; //Response returned
    task = (HttpWebRequest)WebRequest.Create("http://foo.bar/thiswontexistevenifiwishedonedayitwould.html");
    taskresponse = (HttpWebResponse)task.GetResponse();
}

If your test is redirecting to another page during a 404 Selenium could check the final page has what you expect.

Liam
  • 22,818
  • 25
  • 93
  • 157
AutomatedTester
  • 21,440
  • 7
  • 45
  • 62
6

I know this is a shocking hack, but this is what I've done:

    protected void AssertNotYellowScreen()
    {
        var selenium = Selenium;

        if (selenium.GetBodyText().Contains("Server Error in '/' Application."))
        {
            string errorTitle = selenium.GetTitle();

            Assert.Fail("Yellow Screen of Death: {0}", errorTitle);
        }
    }

It gets the job done in the situation I needed it for, although I accept it's not ideal...

5

Since Selenium 2 includes HtmlUnit, you can utilize it in order to get access to the response directly.

public static int getStatusCode(long appUserId) throws IOException {
    WebClient webClient = new WebClient();
    int code = webClient.getPage(
            "http://your.url/123/"
    ).getWebResponse().getStatusCode();
    webClient.closeAllWindows();
    return code;
}
Liam
  • 22,818
  • 25
  • 93
  • 157
Sotomajor
  • 1,386
  • 11
  • 15
3

You probably want to check out the captureNetworkTraffic() call. Right now it only works reliably with Firefox, unless you manually set up IE/Safari/etc to proxy traffic through port 4444.

To use it, just call selenium.start("captureNetworkTraffic=true"), and then later on in your script you can call selenium.captureNetworkTraffic("...") where "..." is "plain", "xml", or "json".

Patrick Lightbody
  • 4,084
  • 1
  • 24
  • 34
0

I haven't tried it, but if you don't mind limiting yourself to Firefox, and installing Firebug and Netexport, then Selenium can get access to the page status code (and everything else in Firebug's Net panel): http://selenium.polteq.com/en/using-netexport-to-export-firebugs-net-panel/

Matthew Lock
  • 11,495
  • 11
  • 84
  • 122
-2

If all else fails you could adapt your server side code, during testing, to output the HTTP status in the page as an element:

For example, on my 403 Permission Denied page, I have:

   <h1 id="web_403">403 Access Denied</h1>

which can be easily checked via the WebDriver API:

    public boolean is403(WebDriver driver) {
        try {
            driver.findElement(By.id("web_403"));
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

https://rogerkeays.com/how-to-get-the-http-status-code-in-selenium-webdriver

Roger Keays
  • 2,798
  • 1
  • 27
  • 22
Matthew Lock
  • 11,495
  • 11
  • 84
  • 122
  • this is **not** checking the HTTP response code, but checking the text content of an element on a page – ccpizza Jul 02 '18 at 15:03
-2

Try this, people

WebClient wc = new WebClient();
int countRepeats = 120; // one wait = 0.5 sec, total 1 minute after this code
boolean haveResult = false;
try {
    HtmlPage pageHndl = wc.getPage(Urls);
    for(int iter=0; iter<countRepeats; iter++){
        int pageCode = pageHndl.getWebResponse().getStatusCode();
        System.out.println("Page status "+pageCode);
        if(pageCode == 200){
            haveResult = true;
            break;
        }
        else{
            Thread.sleep(500);
        }
    }
} catch (IOException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
} catch (InterruptedException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
}
someman
  • 19