Python爬虫库requests获取响应内容、响应状态码、响应头


Posted in Python onJanuary 25, 2020

首先在程序中引入Requests模块

import requests

一、获取不同类型的响应内容

在发送请求后,服务器会返回一个响应内容,而且requests通常会自动解码响应内容

1.文本响应内容

获取文本类型的响应内容

r = requests.get('https://www.baidu.com')
r.text # 通过文本的形式获取响应内容
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>ç\x99¾åo|ä¸\x80ä¸\x8bï¼\x8cä½\xa0å°±ç\x9f¥é\x81\x93</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=ç\x99¾åo|ä¸\x80ä¸\x8b class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ\x96°é\x97»</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>å\x9c°å\x9b¾</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>è§\x86é¢\x91</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>è′′å\x90§</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>ç\x99»å½\x95</a> </noscript> <script>document.write(\'<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=\'+ encodeURIComponent(window.location.href+ (window.location.search === " rel="external nofollow" " ? "?" : "&")+ "bdorz_come=1")+ \'" name="tj_login" class="lb">ç\x99»å½\x95</a>\');\r\n        </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">æ\x9b′å¤\x9aäo§å\x93\x81</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>å\x853äo\x8eç\x99¾åo|</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>使ç\x94¨ç\x99¾åo|å\x89\x8då¿\x85èˉ»</a>  <a href=http://jianyi.baidu.com/ class=cp-feedback>æ\x84\x8fè§\x81å\x8f\x8dé|\x88</a> äo¬ICPèˉ\x81030173å\x8f·  <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'

通过encoding来获取响应内容的编码以及修改编码

r.encoding
'ISO-8859-1'

2.二进制响应内容

r.content # 通过content获取的内容便是二进制类型的

3.JSON响应内容

r.json()

4.原始响应内容

r = requests.get('https://www.baidu.com',stream=True)
print(r.raw) # 就是urllib中的HTTPResponse对象
print(r.raw.read(10))
<requests.packages.urllib3.response.HTTPResponse object at 0x00000077940AEEF0>
b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

二、响应状态码

获取响应状态码

r = requests.get('https://www.baidu.com')
r.status_code
200

判断响应状态码

r.status_code == requests.codes.ok
True

当发送一个错误请求时,抛出异常

bad_r = requests.get('http://httpbin.org/status/404')
print(bad_r.status_code)
bad_r.raise_for_status()
404



---------------------------------------------------------------------------

HTTPError                 Traceback (most recent call last)

<ipython-input-15-9b812f4c5860> in <module>()
   1 bad_r = requests.get('http://httpbin.org/status/404')
   2 print(bad_r.status_code)
----> 3 bad_r.raise_for_status()


D:\Anaconda3\lib\site-packages\requests\models.py in raise_for_status(self)
  926 
  927     if http_error_msg:
--> 928       raise HTTPError(http_error_msg, response=self)
  929 
  930   def close(self):


HTTPError: 404 Client Error: NOT FOUND for url: http://httpbin.org/status/404

三、响应头

获取响应头

r = requests.get('https://www.baidu.com')
r.headers
{'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'Keep-Alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Mon, 23 Jul 2018 09:04:12 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:23:51 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}

获取响应头的具体字段

print(r.headers['Server'])
print(r.headers.get('Server'))
bfe/1.0.8.18
bfe/1.0.8.18

更多关于Python爬虫库requestsr的使用方法请查看下面的相关链接

Python 相关文章推荐
跟老齐学Python之变量和参数
Oct 10 Python
python实现JAVA源代码从ANSI到UTF-8的批量转换方法
Aug 10 Python
解决pycharm界面不能显示中文的问题
May 23 Python
JavaScript中的模拟事件和自定义事件实例分析
Jul 27 Python
Python 通过requests实现腾讯新闻抓取爬虫的方法
Feb 22 Python
浅谈Python反射 &amp; 单例模式
Mar 21 Python
python 中Arduino串口传输数据到电脑并保存至excel表格
Oct 14 Python
opencv3/C++ 平面对象识别&amp;透视变换方式
Dec 11 Python
浅谈selenium如何应对网页内容需要鼠标滚动加载的问题
Mar 14 Python
Python实现七个基本算法的实例代码
Oct 08 Python
Python列表的索引与切片
Apr 07 Python
在 Python 中利用 Pool 进行多线程
Apr 24 Python
使用Python爬虫库requests发送请求、传递URL参数、定制headers
Jan 25 #Python
flask框架自定义url转换器操作详解
Jan 25 #Python
常用python爬虫库介绍与简要说明
Jan 25 #Python
flask框架url与重定向操作实例详解
Jan 25 #Python
flask框架蓝图和子域名配置详解
Jan 25 #Python
flask框架渲染Jinja模板与传入模板变量操作详解
Jan 25 #Python
如何在 Django 模板中输出 &quot;{{&quot;
Jan 24 #Python
You might like
《忧国的莫里亚蒂》先导宣传图与STAFF公开
2020/03/04 日漫
PHP substr 截取字符串出现乱码问题解决方法[utf8与gb2312]
2011/12/16 PHP
php多个字符串替换成同一个的解决方法
2013/06/18 PHP
php生成excel列序号代码实例
2013/12/24 PHP
php微信开发自定义菜单
2016/08/27 PHP
Thinkphp 框架扩展之类库扩展操作详解
2020/04/23 PHP
JQuery 操作Javascript对象和数组的工具函数小结
2010/01/22 Javascript
变量声明时命名与变量作为对象属性时命名的区别解析
2013/12/06 Javascript
js select option对象小结
2013/12/20 Javascript
jquery获取复选框被选中的值
2014/04/10 Javascript
微信小程序 传值取值的几种方法总结
2017/01/16 Javascript
JS区分Object与Aarry的六种方法总结
2017/02/27 Javascript
十大 Node.js 的 Web 框架(快速提升工作效率)
2017/06/30 Javascript
详解angularjs的数组传参方式的简单实现
2017/07/28 Javascript
mpvue 单文件页面配置详解
2018/12/02 Javascript
基于javascript实现日历功能原理及代码实例
2020/05/07 Javascript
vue 中this.$set 动态绑定数据的案例讲解
2021/01/29 Vue.js
Python实现list反转实例汇总
2014/11/11 Python
搭建Python的Django框架环境并建立和运行第一个App的教程
2016/07/02 Python
浅谈五大Python Web框架
2017/03/20 Python
python设定并获取socket超时时间的方法
2019/01/12 Python
python读取有密码的zip压缩文件实例
2019/02/08 Python
pandas 数据结构之Series的使用方法
2019/06/21 Python
利用anaconda作为python的依赖库管理方法
2019/08/13 Python
python输出数学符号实例
2020/05/11 Python
matplotlib之pyplot模块之标题(title()和suptitle())
2021/02/22 Python
实现CSS3中的border-radius(边框圆角)示例代码
2013/07/19 HTML / CSS
HTML5之SVG 2D入门4—笔画与填充
2013/01/30 HTML / CSS
GIVENCHY纪梵希官方旗舰店:高定彩妆与贵族护肤品
2018/04/16 全球购物
护理专业本科生自荐信
2013/10/01 职场文书
中职生自荐信范文
2014/06/15 职场文书
医学专业大学生求职信
2014/07/12 职场文书
2015国际残疾人日活动总结
2015/03/24 职场文书
关于办理居住证的介绍信模板
2019/11/27 职场文书
MySQL数据库必备之条件查询语句
2021/10/15 MySQL
mysql使用 not int 子查询隐含陷阱
2022/04/12 MySQL