python_request的安装及模拟json的post请求及带参数的get请求

一、Requests模块安装

安装方式一:
执行 pip install -U requests 联网安装requests

安装方式二:
进入https://pypi.org/project/requests/
下载并解压requests-***.tar.gz,然后用cmd进入解压目录,使用命令
Python setup.py install 安装requests

在pycham中安装:

 

二、模拟带参数的get请求

import requests

方式一:

get_param_data={
'grant_type':'client_credential',
'appid':'wxc03XXXXXXXXXXX',
'secret':'bc85b7bc56a9cXXXXXXe'
}
response=requests.get(url='https://api.weixin.qq.com/cgi-bin/token',params=get_param_data)
#response.content返回的是Unicode格式,通常需要转换为utf-8格式,否则就是乱码。
response_body=response.content.decode('utf-8')

方式二:

response = requests.get( "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET")
print(response.content.decode( 'utf-8'))

三、模拟json数据格式的post请求

#微信公众号创建标签
url = "https://api.weixin.qq.com/cgi-bin/tags/create"
data = { 'access_token': token_value} #token值为之前获取access_token的值
info = { 'tag':{ 'name':'广州111'}}
headers = { 'Content-Type': 'application/json'} #发送json数据必带的头部信息
response = requests.post(url,params=data,data=json.dumps(info),headers=headers)
print(response.content.decode( 'utf-8'))

备注: json.dumps()用于将dict类型的数据转成json格式编码的字符串

关注1:

post 请求的请求参数是通过data方式来传递的,form表单 (使用dict类型传输):

postResponse = requests.post(url, data={'key': 'value'})

 

posted @ 2020-06-02 22:04  安琪儿一直在  阅读(974)  评论(0编辑  收藏  举报