requests
一、简介
requests
库是Python第三方库,作用是模拟浏览器向服务器发送起HTTP请求,处理响应结果。
requests
库的底层是urllib3
requests库的使用范围:爬虫、接口测试。
-
安装requests库:
python -m pip install requests
-
官方文档:https://docs.python-requests.org/en/master/
-
中文文档:https://docs.python-requests.org/zh_CN/latest/
二、发送请求
GET
import requests
rsp = requests.get('http://httpbin.org/get')
print(rsp) # <Response [200]>
print(type(rsp) # <class 'requests.models.Response'>
POST
import requests
rsp = requests.post('http://httpbin.org/get')
print(rsp) # <Response [200]>
print(type(rsp) # <class 'requests.models.Response'>
三、Response对象
3.1 text方法
text
方法返回响应体,类型为Unicode字符串
- 案例1
import requests
rsp = requests.get('http://httpbin.org/get')
print(rsp.text) # 返回响应体内容
print(type(rsp.text)) # <class 'str'>
- 案例2:访问百度首页
import requests
rsp = requests.get('https://www.baidu.com/')
print(rsp.text) # 结果中的中文显示为乱码
# 查看响应对象的解码格式
print(rsp.encoding) # ISO-8859-1
# 修改解码的格式为UTF-8
rsp.encoding = 'UTF-8'
print(rsp.text) # 正常显示中文
当使用
text
获取响应体时,由于text
会将Bytes
类型的响应内容解码为str
类型,text
会猜测一个解码格式,一般会猜测的格式为ISO-8859-1
;如果需要显示中文,需要指定这个解码格式为
UTF-8
。
3.2 content方法
返回的响应体数据类型为
Bytes
类型,需要进行解码,推荐使用。
import requests
rsp = requests.get('https://www.baidu.com/')
print(rsp.content)
print(type(rsp.content)) # <class 'bytes'>
# 查看响应体的Unicode格式的内容
print(rsp.content.decode()) # 结果为UTF-8解码后的内容
3.3 json对象
- 序列化:将内存中的数据写入到磁盘、传输到网络中的数据转换过程
import json
import requests
rsp = requests.get('http://httpbin.org/get')
print(rsp.json()) # 输出JSON响应体
print(type(rsp.json())) # <class 'dict'>
# JSON序列化
data_json = json.dumps(rsp.json())
print(data_json)
print(type(data_json))