python_requests 库

requests 库是python 常用 第三方库,用来发送网络请求非常简单

具体安装方法就不说了

 

一、发送请求

日常主要使用post 和get  方式请求

1、get 请求 

参数直接放在url中一起请求

url = 'http://wthrcdn.etouch.cn/weather_mini?city=北京'

res = requests.get(url=url)
print('通过get请求:',r_get.json())

使用 params 传参:

传参的数据类型为dict

payload = {'key1': 'value1', 'key2': 'value2'}
res = requests.get("http://httpbin.org/get", params=payload)
print('res.text')

2、post请求

data传参:

当请求的编码格式为:content-type:application/x-www-urlencoded 即键值对传参时,使用data传参,参数类型为dict

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)

当请求的编码格式为:content-type:application/json 即json 字符串 ,也可以使用data进行传参,但是需要对参数进行编码,比如:

import requests,json

post_url = 'https://www.processon.com/search/template'

headers = {'content-type':'application/json;charset=UTF-8'}
reqbody = {"specialId":"","category":"","payType":"","keyword":"框架与逻辑","rows":12,"page":1,"tag":"","sidx":""} 

res = requests.post(url=post_url,data = json.dumps(reqbody ),headers = headers)

print(res.json)

 

json传参:

当请求的编码格式为:content-type:application/json 即json 字符串 ,可以直接通过json直接进行传参

import requests

post_url = 'https://www.processon.com/search/template'

reqbody = {"specialId":"","category":"","payType":"","keyword":"框架与逻辑","rows":12,"page":1,"tag":"","sidx":""}

res = requests.post(url=post_url,json=reqbody)

print(res.json)

 

3、put传参

通过put 传参 

put_url='http://httpbin.org/put'

data = {'key':'value'} res_put = requests.put(url=put_url,data=data) print('通过put请求,',res_put.json())

 

4、通过patch 传参

和put类似

patch_url = 'http://httpbin.org/patch'
data = {'key':'value'}
res_patch = requests.patch(url=patch_url,data=data)
print('通过patch请求,',res_patch.json())

 

上一篇:《叶问》第5期


下一篇:WebAPi性能