Python教程

python_requests 库

本文主要是介绍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())

 

这篇关于python_requests 库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!