如何使用 Selenium WebDriver 获取 HTTP 响应代码
我已经使用 Selenium2/WebDriver 编写了测试,并且想要测试 HTTP 请求是否返回 HTTP 403 Forbidden。
是否可以使用 Selenium WebDriver 获取 HTTP 响应状态代码?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
一句话,不。使用 Selenium WebDriver API 是不可能的。该项目的问题跟踪器中对此进行了令人厌烦的讨论,并且该功能不会添加到 API 中。
In a word, no. It's not possible using the Selenium WebDriver API. This has been discussed ad nauseam in the issue tracker for the project, and the feature will not be added to the API.
可以使用 Selenium 和 Chrome 或 Firefox 获取 http 请求的响应代码。您所要做的就是在日志模式下启动 Chrome 或 Firefox。下面我将向您展示一些例子。
java + Selenium + Chrome
这是 java + Selenium + Chrome 的示例,但我想它可以用任何语言完成(python,c#,...)。
您需要做的就是告诉 chromedriver 执行“Network.enable”。这可以通过启用性能日志记录来完成。
请求完成后,您所要做的就是获取并迭代性能日志,并找到请求的 url 的“Network.responseReceived”:
这是代码:
输出如下所示:
java + Selenium + Firefox< /强>
我终于也找到了 Firefox 的窍门。您需要使用
MOZ_LOG
和MOZ_LOG_FILE
环境变量启动 Firefox,并在调试级别记录 http 请求(4 = PR_LOG_DEBUG) - map.put("MOZ_LOG", “时间戳,同步,nsHttp:4”)
。将日志保存在临时文件中。之后,获取保存的日志文件的内容并解析它的响应代码(使用一些简单的正则表达式)。首先检测请求的开始,识别其 id(nsHttpChannel::BeginConnect [this=000000CED8094000])
,然后在第二步中找到该请求 id 的响应代码(nsHttpChannel: :ProcessResponse [this=000000CED8094000 httpStatus=200])
。其输出将是
响应标头也可以在日志文件中找到。如果你愿意的话你可以得到它们。
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.
对于那些使用 Python 的人,您可能会考虑 Selenium Wire,一个用于检查浏览器发出的请求的库在测试期间。
您可以通过 driver.requests 属性访问请求:
Prints:
该库使您能够访问标头、状态代码、正文内容,以及修改标头和重写 URL 的能力。
For those people using Python, you might consider Selenium Wire, a library for inspecting requests made by the browser during a test.
You get access to requests via the
driver.requests
attribute:Prints:
The library gives you the ability to access headers, status code, body content, as well as the ability to modify headers and rewrite URLs.
您可以使用 BrowserMob 代理通过 HttpRequestInterceptor 捕获请求和响应。这是 Java 中的一个示例:
You can use BrowserMob proxy to capture the requests and responses with a
HttpRequestInterceptor
. Here is an example in Java:获取任何语言的响应代码(使用 JavaScript):
如果您的 Selenium 测试在现代浏览器中运行,获取响应代码的一个简单方法是发送同步
XMLHttpRequest
* 并检查status
:您可以在任何编程中使用此技术通过请求 Selenium 执行脚本来调用语言。例如,在 Java 中,您可以使用
JavascriptExecutor.executeScript()
发送XMLHttpRequest
:* 您可以发送相反,异步
XMLHttpRequest
,但您需要等待它完成才能继续测试。Java 中获取响应码:
您可以使用
URL.openConnection()
和HttpURLConnection.getResponseCode()
:此方法也可能推广到其他语言,但需要进行修改以适应该语言(或库)的 API。
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.
我也遇到了同样的问题并卡住了几天,但经过一些研究,我发现我们实际上可以使用 chrome 的“--remote-debugging-port”与 selenium web 驱动程序结合拦截请求。
使用以下伪代码作为参考:-
通过远程调试创建 chrome 驱动程序的实例
对 http://127.0.0.1:freePort
提取chrome的webSocket Url来监听,你可以看到响应并弄清楚如何提取
连接到这个套接字,您可以使用asyncHttp
启用网络捕获
现在chrome将发送所有网络相关事件并捕获它们,如下
您可以执行开发工具站点中提到的所有操作。
请参阅 https://chromedevtools.github.io/devtools-protocol/
注意:- 使用 chromedriver 2.39 或更高版本。
我希望它能帮助某人。
参考:使用 Google Chrome 远程调试协议
I was also having same issue and stuck for some days, but after some research i figured out that we can actually use chrome's "--remote-debugging-port" to intercept requests in conjunction with selenium web driver.
Use following Pseudocode as a reference:-
create instance of chrome driver with remote debugging
make a get call to http://127.0.0.1:freePort
Extract chrome's webSocket Url to listen, you can see response and figure out how to extract
Connect to this socket, u can use asyncHttp
Enable network capture
Now chrome will send all network related events and captures them as follows
you can do everything mentioned in dev tools site.
see https://chromedevtools.github.io/devtools-protocol/
Note:- use chromedriver 2.39 or above.
I hope it helps someone.
reference : Using Google Chrome remote debugging protocol
不确定这就是你要找的,但我有一个不同的目标是检查远程图像是否存在并且我不会出现 403 错误,所以你可以使用如下所示的内容:
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:
直接使用 Selenium WebDriver 无法获取 HTTP 响应代码。该代码可以通过Java代码获得,并且可以在Selenium WebDriver中使用。
要通过 java 获取 HTTP 响应代码:
现在您可以编写 Selenium WebDriver 代码,如下所示:
It is not possible to get HTTP Response code by using Selenium WebDriver directly. The code can be got by using Java code and that can be used in Selenium WebDriver.
To get HTTP Response code by java:
Now you can write your Selenium WebDriver code as below:
你可以尝试 Mobilenium (https://github.com/rafpyprog/Mobilenium),一个 python 包绑定 BrowserMob 代理和 Selenium。
使用示例:
You could try Mobilenium (https://github.com/rafpyprog/Mobilenium), a python package that binds BrowserMob Proxy and Selenium.
An usage example:
简单的一个衬垫即可返回 GET 请求的响应状态和文本。
Simple one liner to return response status and text for GET request.