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 相关文章推荐
数据挖掘之Apriori算法详解和Python实现代码分享
Nov 07 Python
python 查找字符串是否存在实例详解
Jan 20 Python
python生成器与迭代器详解
Jan 01 Python
Python动态赋值的陷阱知识点总结
Mar 17 Python
PyQt5 实现字体大小自适应分辨率的方法
Jun 18 Python
连接pandas以及数组转pandas的方法
Jun 28 Python
代码总结Python2 和 Python3 字符串的区别
Jan 28 Python
Python yield的用法实例分析
Mar 06 Python
Python 统计位数为偶数的数字代码详解
Mar 15 Python
Keras 利用sklearn的ROC-AUC建立评价函数详解
Jun 15 Python
Python collections模块的使用方法
Oct 09 Python
python通配符之glob模块的使用详解
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
PHP初学者头疼问题总结
2006/10/09 PHP
dede3.1分页文字采集过滤规则详说(图文教程)续二
2007/04/03 PHP
php实现mysql同步的实现方法
2009/10/21 PHP
php使用memcoder将视频转成mp4格式的方法
2015/03/12 PHP
php结合安卓客户端实现查询交互实例
2015/05/05 PHP
PHP的邮件群发系统phplist配置方法详细总结
2016/03/30 PHP
利用PHP如何统计Nginx日志的User Agent数据
2019/03/06 PHP
给Function做的OOP扩展
2009/05/07 Javascript
让FireFox支持innerText的实现代码
2009/12/01 Javascript
jquery处理json数据实例分析
2014/06/03 Javascript
js计算文本框输入的字符数
2015/10/23 Javascript
sso跨域写cookie的一段js脚本(推荐)
2016/05/25 Javascript
Jquery循环截取字符串的方法(多出的字符串处理成&quot;...&quot;)
2016/11/28 Javascript
完全深入学习Bootstrap表单
2016/11/28 Javascript
js实现百度搜索提示框
2017/02/05 Javascript
JS正则获取HTML元素的方法
2017/03/31 Javascript
详解vue移动端日期选择组件
2018/02/22 Javascript
JS实现调用本地摄像头功能示例
2018/05/18 Javascript
讲解vue-router之命名路由和命名视图
2018/05/28 Javascript
Angular ui-roter 和AngularJS 通过 ocLazyLoad 实现动态(懒)加载模块和依赖
2018/11/25 Javascript
ligerUI的ligerDialog关闭刷新的方法
2019/09/27 Javascript
Django中URLconf和include()的协同工作方法
2015/07/20 Python
Python中Django框架利用url来控制登录的方法
2015/07/25 Python
使用Python脚本生成随机IP的简单方法
2015/07/30 Python
python DataFrame 取差集实例
2019/01/30 Python
基于Python实现视频的人脸融合功能
2020/06/12 Python
如何用python批量调整视频声音
2020/12/22 Python
python基于爬虫+django,打造个性化API接口
2021/01/21 Python
解决PDF 转图片时丢文字的一种可能方式
2021/03/04 Python
HTML5 对各个标签的定义与规定:body的介绍
2012/06/21 HTML / CSS
经济学人订阅:The Economist
2018/07/19 全球购物
留学推荐信怎么写
2014/01/25 职场文书
小学阳光体育活动总结
2014/07/05 职场文书
小学班主任个人总结
2015/03/03 职场文书
2015安全保卫工作总结
2015/04/25 职场文书
python字符串的多行输出的实例详解
2021/06/08 Python