request模块基本使用方法

一、前言

官方文档:https://requests.readthedocs.io/en/latest/

模块安装:pip install request

二、请求

2.1 请求方式

常用请求方法:getpost

请求方法含义
get向特定的资源发出请求
post向指定资源提交数据进行处理请求(例如提交表单或者上传文件)
put向指定资源位置上传其最新内容
delete请求服务器删除Request-URL所标识的资源
options返回服务器针对特定资源所支持的HTTP请求方法
head向服务器索要与GET请求相一致的响应,只不过响应体将不会被返回

2.2 请求参数

常用请求参数:

请求参数含义
url请求的url,必选参数
params请求参数
headers请求头
data表单数据

详细参数解析:

params参数:一般用来在url的查询字符串发送数据

payload = {'key1': 'value1', 'key2': 'value2'}

r = requests.get('https://httpbin.org/get', params=payload)
# url:https://httpbin.org/get?key2=value2&key1=value1

stream参数:流式传送数据,可以用来将数据分流进行下载,搭配response.iter_content使用

r = requests.get('https://api.github.com/events', stream=True)

with open(filename, 'wb') as fd:
    for chunk in r.iter_content(chunk_size=128):
        fd.write(chunk)

headers参数:向请求添加http标头,所有标头值必须是字符类型

url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}

r = requests.get(url, headers=headers)

一些常用的请求头:

请求头含义
user-agent与浏览器或其他生成请求的客户端软件有关的信息
referer发出请求的原始URL
cookie提交服务器向客户端发布的其他参数

data参数:发送表单数据,表单数据可以为元组列表或者字典类型

payload = {'key1': 'value1', 'key2': 'value2'}

r = requests.post('https://httpbin.org/post', data=payload)

json参数::发送json类型的表单数据

import json

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}

# r = requests.post(url, data=json.dumps(payload))
r = requests.post(url, json=payload)

proxies参数:

proxies = 
{
    "http" : "http://127.0.0.1:8888",
    "https" : "https://"127.0.0.1:8888",
}
requests.get(url, proxies = proxies)

files参数:上传文件,可以设置文件名,内容类型,头部信息,或者直接传送数据

url = 'https://httpbin.org/post'

files = {'file': open('report.xls', 'rb')}
# files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
# files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}

r = requests.post(url, files=files)

文件较大时,可以采用流式上传(建议用二进制模式打开):

with open('massive-body', 'rb') as f:
    requests.post('http://some.url/streamed', data=f)

allow_redirects参数:默认情况下,requests发送的请求除了head之外,都会自动进行重定向,可以通过设置allow_redirects值为False来取消重定向。

url = 'https://api.github.com/some/endpoint'

r = requests.get(url, allow_redirects = False)

verify参数:向网站发送请求时,会像 Web 浏览器一样验证 HTTPS 请求的 SSL 证书。如果无法验证证书,将抛出 SSLError;可以令verify=False也可以将ssl证书路径传递给verify参数。

url = 'https://api.github.com/some/endpoint'

# r = requests.get(url, verify = False)
r = requests.get(url, verify='/path/to/certfile')

timeout参数:通过设置timeout,可以强制请求要在特定的时间内返回结果,否则就报错。

url = 'https://api.github.com/some/endpoint'

r = requests.get(url, timeout = 1)

除此之外,也可以使用retrying模块来刷新网页,模块安装:pip install retrying。retry方法可以在函数报错后重新执行,stop_max_attempt_number为最大刷新次数。

from retrying import retry

@retry(stop_max_attempt_number=3) #最大刷新次数为3
def test():
    url = 'https://api.github.com/some/endpoint'
    r = requests.get(url, timeout = 1)
    assert r.status_code == 200 # 不是200,也会报错
    return r


if __name__ == '__main__':
    try:
        r = test()
    except Exception as e:
        print("error")
        r = None

2.3 cookie

(1)原理:由于http是无状态协议,一旦客户端和服务器的数据交换完毕,就会断开连接,再次请求会重新连接。为了让服务器知道用户身份,那就在每次请求时带上cookie(身份证),这样就能针对不同用户做出不同响应。

(2)分类:cookie按照过期时间分为:会话cookie持久cookie。会话cookie在用户退出浏览器时就会删除;而持久cookie无论是退出浏览器,还是重启电脑它依然存在,但持久cookie通常会有过期时间或者有效期

(3)添加cookies的方式:

  1. 直接添加到headers中:

    url = 'https://httpbin.org/cookies'
    headers = {
        'cookies_name' : "cookies_values"
    }
    
    r = requests.get(url, headers=headers)
    
  2. 传给cookies参数:

    url = 'https://httpbin.org/cookies'
    cookies = { "cookies_name" : "cookies_values"}
    
    r = requests.get(url, cookies=cookies)
    
  3. 获取响应提取cookies:

    url = 'https://httpbin.org/cookies'
    r = requests.get(url)
    
    cookies = requests.utils.dict_from_cookiejar(r.cookies)
    
  4. 使用session模块:session能够自动带上前一次请求的cookie

    s = requests.Session()
    r = s.get(url , headers)
    

三、响应

response常用属性:

属性含义
text响应体,str类型
content响应体,bytes类型
url响应url
status_code响应状态码
request.headers请求头
headers响应头
encoding编码
history请求历史

常见状态码:

状态码含义
100 Continue已收到请求消息头,客户端应继续发送主体。请求完成后,再由服务器返回另一个响应。
200 Ok成功提交请求
301 Moved Permanently将浏览器永久重定向到另外一个在Location消息头中指定的URL
302 Found将浏览器暂时重定向到另外一个在Location消息头中指定的URL,客户端应在随后的请求中恢复使用原始URL.
400 Bad Request客户端提交了一个无效的HTTP请求
401 Unauthorized服务器在许可请求前要求HTTP进行身份验证。
403 Forbidden不管是否通过身份验证,禁止任何人访问被请求的资源。
404 Not Found所请求的资源并不存在。
405 Method Not Allowed指定的URL不支持请求中使用的方法。
500 Internal Server Error服务器在执行请求时遇到错误
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值