Python爬虫库requests获取响应内容、响应状态码、响应头
作者:BQW_ 发布时间:2022-05-03 14:37:27
标签:Python爬虫,requests
首先在程序中引入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
来源:https://blog.csdn.net/bqw18744018044/article/details/81171220


猜你喜欢
- 为什么使用虚拟环境因为直接在真实环境进行安装python的包会造成环境之间的污染,因此需要创建虚拟环境,原则上每一个项目都需要有一个独属于自
- 1. 云开发简介由于小程序本身存储数据的能力有限,所以不可能将大量的数据保存在客户端,而且将数据保存在本地既不安全,也无法与其他小程序用户共
- 1.添加新用户只允许本地IP访问create user 'test'@'localhost' identif
- 废话不多说了,直奔主题了。mysql的四种启动方式:1、mysqld启动mysql服务器:./mysqld --defaults-file=
- 最近在使用linux上进行本地登录时,发现既然无法正常登录 , 报如下错误信息:[root@xxxx ~]# mysql -h localh
- opts, args = getopt.getopt(sys.argv[1:], "t:s:h", ["wal
- 不固定参数函数在go语言中,允许对函数设置不固定参数。不过需要注意的是,虽然不限制参数数量,但限制了参数的数据类型。从原理分析,不固定参数利
- 运行下面存储过程 然后直接使用 SpaceUsed 就可以查看了. 存储过程代码 程序代码 Create&n
- 1. *表示匹配任意多个字符 \d*表示匹配任意多个数字字符import retext = "
- 本文实例为大家分享了python3判断IP地址的具体代码,供大家参考,具体内容如下输入一串字符,判断该字符串是否为点分十进制的IP地址,若是
- 前言读取站点资料数据对站点数据进行插值,插值到规则网格上绘制EOF第一模态和第二模态的空间分布图绘制PC序列关于插值,这里主要提供了两个插值
- 在数据库查询的时候,我们有时有这样的需求,就是要找出数据表里指定范围行内的数据记录,比如说要找出数据表里第10行到第20行的这10条数据,那
- 环境:Python3.6.4 + pandas 0.22主要是DataFrame.apply函数的应用,如果设置axis参数为1则每次函数每
- 时钟实现实现这个时钟时间需要解决以下三个问题:获得当前时间,并格式化如何可以在页面中显示时间让时间动起来1、获得当前时间,并格式化要获得当前
- WebSocketWebSocket说明WebSocket 是全双工网络通信通信协议,实现了客户端和服务器的平等对话,任何一方都可以主动发送
- Python项目中很多时候会需要将时间在Datetime格式和TimeStamp格式之间转化,又或者你需要将UTC时间转化为本地时间,本文总
- 作为收费应用方面的数据库管理员(DBA),公司首席信息官(CIO)经常邀请我与Sarbanes-Oxley审查员开会讨 * 司数据的安全与整合
- 目录简介环境要求:安装小试一下创建爬虫将请求头转为json格式使用简介feapder 是一款上手简单,功能强大的Python爬虫框架,使用方
- 0. 前言这几天在写软件工程课设,题目是:设计一款疫苗管理系统,于是用PyQT5写GUI,MySQL做数据库写了一个demo出来。做完之后,
- vue控制mock在开发环境使用,在生产环境禁用说下原因mock拦截所有的axios请求,根据请求,做出相应的响应。平时前后端分离开发,我们