r = requests.request(method, url, **kwargs)
# method请求方法,共get\post\put\patch\delete\head
# url, 请求地址
# **kwargs,参数param,cookies,auth,headers,file,data,json,timeout,proxies字典类型,设定访问代理服务器,allow_redirects 重定向开关,stream 获取内容立即下载开关,verity 认证ssl证书开关,cert 本地ssl证书路径
1、get请求的params参数,添加到网址后面
import requests
kv = {'key1': 'value1', 'key2': 'value2'}
r = requests.request('GET', 'http://python123.io/ws', params=kv)
print(r.request.url)
# 结果:https://www.baidu.com/?key1=value1&key2=value2
#获取headers\cookies
r.headers.get('content-type')
r.cookies['cookie_name']
【注意:请求参数为dict格式;
重点:发送请求赋值的res,可以看成是请求的上下文,即可以获取请求相关参数值,也可以获取响应相关参数值。】
2、post请求的data
data:字典、字节序列或文件对象,作为Requests的内容
import requests
data = {'key1': 'value1', 'key2': 'value2'}
r = requests.request('POST', 'http://python123.io/ws', data=data)
print(r.request.body)
#查看内容:key1=value1&key2=value2
【若无请求参数可不传data;如传参数需为dict格式】
3、json格式的数据
import requests
data = {'key1': 'value1', 'key2': 'value2'}
#将post请求中的data参数转为json格式的两种方式:改为json,或 将字典对象转为json字符串
res1 = requests.request('POST', url, headers=headers, data=json.dumps(data))
r = requests.request('POST', 'http://python123.io/ws', json=data)
4、headers、cookies:字典,http定制头;
"""自定义headers"""
import requests
hr = {'key1': 'value1'}
r = requests.request('GET', 'http://python123.io/ws', headers=hr)
print(r.request.headers)
#结果:{'User-Agent': 'python-requests/2.20.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'key1': 'value1'}
"""自定义cookies"""
cookies = dict(cookies_are='working')
cookies2 = {'cookies_are': 'working'}
r = requests.request('GET', 'http://python123.io/ws', cookies=cookies)
print(r.json())
5、其他类型请求
r = requests.put('http://httpbin.org/put', data={'key':'value'}).text
r = requests.delete('http://httpbin.org/delete').text
r = requests.head('http://httpbin.org/head').text
6、响应内容
url = 'http://python123.io/ws'
param = {
'username': '123',
'password': '321'
}
res = requests.get(url, params=param)
print('请求url:' + res.url)
print('响应内容 json格式:' + json.dumps(res.json()))
print('响应内容 字符串格式:'+ res.text)
print('响应内容 二进制格式:'+ str(res.content))
print('响应码:'+ str(res.status_code))
通用方式
get请求: requests.get(url, params=None,kwargs) params是url中额外参数,可省略,kwargs是另外的12个控制访问的参数
post请求: requests.post(url, data=None,json=None,**kwagrs)
head请求:requests.head(url, **kwargs)
put请求:requests.put(url, data=None, **kwargs)
patch请求:requests.patch(url, data=None, **kwargs)
delete请求:requests.delete(url, **kwargs)