requests基础(一)-requests模拟get请求、post请求
requests安装
pip install requests
requests模拟get请求
response.content 是二进制模式,通常需要转换成UTF-8模式,否则会乱码
以请求淘宝主页为例
#requests模拟get请求、
import requests
response=requests.get('https://www.taobao.com/')
# 方式一:
# print(response.content.decode('utf-8')) #response.content 二进制模式
# 方式二
response.encoding='utf-8'
print(response.text)
requests模拟带参数的get请求
以微信公众号接口平台为例,其中appid和secret值获取方式为:
1、进入微信公众平台开发者文档:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
2、进入开始开发-接口测试号申请菜单,点击进入微信公众帐号测试号申请系统
3、通过微信扫一扫生成测试号,生成appid和secret
#模拟带参数的get请求
import requests
#方式一
# response=requests.get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx93fc8716b3795e89&secret=1ff879affa4d6c7cddc27b2e99406988')
# print(response.content.decode('utf-8'))
# 方式二
get_param_data={
"grant_type":"client_credential",
"appid":"wx93fc8716b3795e89",
"secret":"1ff879affa4d6c7cddc27b2e99406988"
}
response=requests.get('https://api.weixin.qq.com/cgi-bin/token',get_param_data)
print(response.content.decode('utf-8'))
requests模拟请求头
以百度搜索为例,如果没有添加User-Agent头部信息,则返回的数据是错误的
#requests模拟请求头
import requests
get_param_data={
"wd":"天天向上"
}
head_info={
"User-Agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Mobile Safari/537.36",
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding":"gzip, deflate, br",
"Accept-Language":"zh-CN,zh;q=0.9"
}
response=requests.get(url='https://www.baidu.com/s',params=get_param_data,headers=head_info)
print(response.content.decode('utf-8'))
requests模拟post请求
post请求的请求参数时通过data方式来传递的,post的请求方式一般有form表单、json数据、文件等
# requests模拟post请求 post数据体为json格式时,两种方式
import requests
import json
get_param_data={
'access_token':'46_y-hzaypfU1iN6yRG5-fK1R-bIxictGTUdF6nlelsad6Bwb1TrnIRYPdUtkgC93I9FAcLcDpk0p4R1yRZiZUjioTuMzueO-BG74mc0vgj30zjNvCYaipXuyuJ8bgGyPiFmyLjx7uHjQ_GMa1AJTNaAHANXR'
}
post_param_data={"tag": {"id":103,"name":"上海话7"}}
header_info={'Content-Type':'application/json'}
response=requests.post(url='https://api.weixin.qq.com/cgi-bin/tags/update',
params=get_param_data,
data=json.dumps(post_param_data), #方式一
# json=post_param_data,#方式二
headers=header_info
)
print(response.content.decode('utf-8'))
#requests模拟post请求:文件上传
import requests
#简单文件
excel_file={"file":open("testdata.xlsx","rb")}
#复杂文件
excel_file={"file":('testdata.xlsx',open('testdata.xlsx','rb'),'application/vnd.ms-excel',{'Expires':'0'})}
response=requests.post(url='http://httpbin.org/post',
files=excel_file
)
print(response.content.decode('utf-8'))