python-requests模块学习
1. 安装及导入模块
pip install requests
import requests
2. 发送请求
各类请求方法
r = requests.get('https://www.baidu.com') #GET请求
r = requests.post('https://www.baidu.com') #POST请求
r = requests.put('https://www.baidu.com') #PUT请求
r = requests.delete('https://www.baidu.com') #DELETE请求
r = requests.head('https://www.baidu.com') #HEAD请求
r = requests.options('https://www.baidu.com') #OPTIONS请求
定制请求头
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
3. 传递参数
GET请求
payload = {'username': 'admin', 'password': 'admin'}
r = requests.get("http://192.168.1.10/login", params=payload)
print(r.url) #http://192.168.1.10/login?username=admin&password=admin
POST请求
r = requests.post('http://192.168.1.10/login', data = {'key':'value'})
4. 获取响应内容
普通文本
r.encoding='UTF-8' #设置响应编码
print(r.content) #以十六进制方式显示内容,是bytes类型
print(r.text) #以文本方式显示内容
图片数据
url='https://img2020.cnblogs.com/blog/2552720/202111/2552720-20211101185253279-95385767.png'
r = requests.get(url)
i = Image.open(BytesIO(r.content)) #使用字节流的形式打开图片
i.show() #显示图片
i.save('./dog.png') #保存图片
JSON数据
url='https://api.github.com/events'
r = requests.get(url)
print(r.json())
响应状态码
r = requests.get('http://www.baidu.com')
print(r.status_code)
响应头
r = requests.get('http://www.baidu.com')
print(r.headers)