1.简介
requests是一个很实用的Python HTTP客户端库,编写爬虫和测试服务器响应数据时经常会用到,Requests是Python语言的第三方的库,专门用于发送HTTP请求
2.下载
pip install requests
3.引用
import requests
4.请求方式
GET:
import requests
# requests.get()方法发送的是GET请求,因此不需要设置data参数,应该使用params参数来传递请求参数,params=
response = requests.get('https://www.baidu.com')
# 响应状态码: 200
print('响应状态码:', response.status_code)
# 请求网络地址 https://www.baidu.com/
print('请求网络地址:', response.url)
# 请求头信息 {'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Mon, 28 Mar 2022 13:01:40 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:23:55 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('请求头信息:', response.headers)
# cookie信息 <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
print('cookie信息', response.cookies)
# 设置编码 防止乱码
response.encoding = 'utf-8'
# 文本的形式打印
print(response.text)
POST:
import requests # 导入网络请求模块requests
import json # 导入json模块
# requests.post()方法发送的是POST请求,因此需要设置data参数,json=
# 登录获取token
def login():
# url
url = "http://127.0.0.1:8888/login"
# 请求头类型
header = {"Content-Type": "application/json"}
# 请求参数
data = {
"code": 1,
"password": 123456,
"username": "xxx"
}
# 发送post接口请求获取响应结果并转为json格式后提取token
try:
res = requests.post(url=url, headers=header, json=data)
response = res.json()
response_token = response['data']
token = response_token['access_token']
print(token)
except Exception as e:
print("获取Token失败:", str(e))