I have written tests with Selenium2/WebDriver and want to test if HTTP Request returns an HTTP 403 Forbidden.
Is it possible to get the HTTP response status code with Selenium WebDriver?
I have written tests with Selenium2/WebDriver and want to test if HTTP Request returns an HTTP 403 Forbidden.
Is it possible to get the HTTP response status code with Selenium WebDriver?
Obtain the Response Code in Any Language (Using JavaScript):
If your Selenium tests run in a modern browser, an easy way to obtain the response code is to send a synchronous
XMLHttpRequest
* and check thestatus
of the response:You can use this technique with any programming language by requesting that Selenium execute the script. For example, in Java you can use
JavascriptExecutor.executeScript()
to send theXMLHttpRequest
:* You could send an asynchronous
XMLHttpRequest
instead, but you would need to wait for it to complete before continuing your test.Obtain the Response Code in Java:
You can obtain the response code in Java by using
URL.openConnection()
andHttpURLConnection.getResponseCode()
:This method could probably be generalized to other languages as well but would need to be modified to fit the language's (or library's) API.
It is possible to get the response code of a http request using Selenium and Chrome or Firefox. All you have to do is start either Chrome or Firefox in logging mode. I will show you some examples below.
java + Selenium + Chrome Here is an example of java + Selenium + Chrome, but I guess that it can be done in any language (python, c#, ...).
All you need to do is tell chromedriver to do "Network.enable". This can be done by enabling Performance logging.
After the request is done, all you have to do is get and iterate the Perfomance logs and find "Network.responseReceived" for the requested url:
Here is the code:
The output looks like this:
java + Selenium + Firefox I have finally found the trick for Firefox too. You need to start firefox using
MOZ_LOG
andMOZ_LOG_FILE
environment variables, and log http requests at debug level(4 = PR_LOG_DEBUG) - map.put("MOZ_LOG", "timestamp,sync,nsHttp:4")
. Save the log in a temporary file. After that, get the content of the saved log file and parse it for the response code (using some simple regular expressions). First detect the start of the request, identifying its id(nsHttpChannel::BeginConnect [this=000000CED8094000])
, then at the second step, find the response code for that request id(nsHttpChannel::ProcessResponse [this=000000CED8094000 httpStatus=200])
.The output for this will be
The response headers can also be found in the log file. You can get them if you want.
Not sure this is what you're looking for, but I had a bit different goal is to check if remote image exists and I will not have 403 error, so you could use something like below: