phantomjs – 如何从page.open请求中查看HTTP状态代码?

前端之家收集整理的这篇文章主要介绍了phantomjs – 如何从page.open请求中查看HTTP状态代码?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个phantomJS脚本,其中包含以下内容
  1. page.open(url,function (status) {
  2. if (status === "fail") { /* handle failure */ }
  3. });

状态检查有时会起作用,但即使请求返回500,状态仍将是“成功”.如何获取实际的请求状态代码

解决方法

你可以这样做:
  1. var page = require('webpage').create(),system = require('system'),resources = [];
  2.  
  3. page.open('http://google.com',function (status) {
  4. console.log('Loaded with http status:',resources[0].status);
  5. phantom.exit();
  6. });
  7.  
  8. page.onResourceReceived = function(response) {
  9. // check if the resource is done downloading
  10. if (response.stage !== "end") return;
  11. // apply resource filter if needed:
  12. if (response.headers.filter(function(header) {
  13. if (header.name == 'Content-Type' && header.value.indexOf('text/html') == 0) {
  14. return true;
  15. }
  16. return false;
  17. }).length > 0)
  18. resources.push(response);
  19. };

因此,如果您需要检查第一个浏览器请求的状态(在本例中为google的html页面),您应该将其视为资源[0] .status中返回的第一个请求.在onResourceReceived处理程序中,您可以为尝试从中获取http代码的资源添加更多过滤器.

更新:感谢@fotijr,添加了对已完成回复的检查

猜你在找的JavaScript相关文章