Requests库详解
目标
● 什么是Requests?
● Requests用法讲解
01.什么是Requests
Requests是用Python语言编写,基于urllib,采用Apache2 Licensed开源协议的HTTP库。它比urllib更加方便,可以节约我们大量的工作,完全满足HTTP测试的请求。
一句话:Python实现的简单易用的HTTP库。
02.Requests用法讲解
● 实例引入:
import requests
response = requests.get('https://www.baidu.com/')
print(type(response))
print(response.status_code)
print(type(response.text))
print(response.text)
print(response.cookies)
● 各种请求方式:
只有部分请求,全部的请求可以到http://httpbin.org 网页查看
import requests
# 1、post 方法
req_post = requests.post('http://httpbin.org/post')
# 用text将请求的内容输出
print(req_post.text)
print("")
# 2、put方法
req_put = requests.put('http://httpbin.org/put')
print(req_put.text)
print("")
# 3、delete方法
req_delete = requests.delete('http://httpbin.org/deldte')
print(req_delete.text)
print("")
# 4、head 方法
req_head = requests.head('http://httpbin.org/head')
print(req_delete.text)
print("")
# 5、options 方法
req_options = requests.options('http://httpbin.org/options')
print(req_options.text)
2.1 GET请求
(1)基本GET请求
import requests
response = requests.get('http://httpbin.org/get')
print(response.text)
(2)带参数的GET请求
import requests
# 方法一
response1 = requests.get('http://httpbin.org/get?name=Andy&age=22')
print(response1.text)
# 方法2
data = {'name': 'Andy', 'age': 22}
response2 = requests.get('http://httpbin.org/get', params=data)
print(response2.text)
(3)解析json
import requests
import json
response = requests.get('http://httpbin.org/get')
print(type(response.text))
print(response.json())
print(type(response.json()))
print(json.loads(response.text))
response.json() = json.loads()
(4)获取二进制数据
import requests
response = requests.get('http://github.com/favicon.ico')
print(type(response.text), type(response.content))
print(response.text)
print(response.content)
# 保存
with open('favicon.ico','wb') as f:
f.write(response.content)
f.close()
(5)添加headers
import requests
# 没有请求头,请求失败
response1 = requests.get("http://www.zhihu.com/explore")
print(response1.text)
# 有请求头,请求成功
headers = {'User-Agent': 'Mozilla/5.0(Macintosh;Intel Mac OS X 10_11_4)AppleWebKit/537.36(KHTML, like Gecko) Chrome/52.0.2743.116 Safair/537.36'}
response2 = requests.get("http