Python通过requests模块发起HTTP请求
一、检查requests是否已安装
查看已安装的模块
pip list
列表没有requests模块则需要安装。
二、安装requests模块
安装requests模块
pip install requests
三、发起HTTP请求
分别发起get和post请求,完整示例代码
import requests
# 设置查询参数
params = {"keyword": 'test'}
# 设置请求头
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
# 设置提交的数据
data = {"name": "fun", "age": 100}
'''发起get请求'''
response = requests.get('https://www.befun.ink/test/health-check', params=params, headers=headers)
'''发起post请求'''
response = requests.post('https://www.befun.ink/test/health-check', params=params, headers=headers, data=data)
print(response.text) # 返回接口内容
print(response.status_code) # 返回HTTP状态码
print(response.headers) # 返回HTTP响应头
print(response.url) # 返回响应请求的链接地址
print(response.cookies) # 返回Cookies
print(response.reason) # 响应描述
print(response.apparent_encoding) # 返回编码
print(response.json()) # 返回json格式数据