加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

【python】requests模块初探(一)

发布时间:2020-12-20 10:31:32 所属栏目:Python 来源:网络整理
导读:一、写在前面 Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库。它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求。Requests 的哲学是以 PEP 20 的习语为中心开发的,所以它比 urllib 更加 Pyth

一、写在前面


Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库。它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求。Requests 的哲学是以 PEP 20 的习语为中心开发的,所以它比 urllib 更加 Pythoner。

那么,requests都有哪些应用场景呢?

1.服务器编程基础;

2.爬虫利器;

3.自动化接口测试;

4.运维监控脚本

等等

本篇,我就记录一下requests最常用的两个请求方式和以及响应,其他内容后续更新


二、安装

安装很简单,只需要使用命令行安装即可:

pip install requests

三、请求

3.1 GET请求

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

3.2 传递URL参数的GET请求

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

3.3 请求cookies

url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url,cookies=cookies)
#后面用到再详细分析

3.4 POST请求

通常,想要发送一些编码为表单形式的数据——非常像一个 HTML 表单。要实现这个,只需简单地传递一个字典给 data 参数。你的数据字典在发出请求时会自动编码为表单形式:

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

还可以为 data 参数传入一个元组列表。在表单中多个元素使用同一 key 的时候,这种方式尤其有效:

payload = (('key1','value1'),('key1','value2'))
r = requests.post('http://httpbin.org/post',data=payload)

很多时候你想要发送的数据并非编码为表单形式的,例如你要传递一个 string 而不是一个 dict:

import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url,data=json.dumps(payload))

或者是定义一个字符串的data

url = 'https://api.github.com/some/endpoint'
payload = '{"some": "data"}'
r = requests.post(url,data=payload)

此处除了可以自行对 dict 进行编码,你还可以使用 json 参数直接传递,然后它就会被自动编码

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url,json=payload)

四、请求头

如果想为请求添加 HTTP 头部,只要简单地传递一个 dict 给 headers 参数就可以了。

url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url,headers=headers)

五、响应

前面的请求例子中,每个请求都会赋值给一个名为 r 的 Response 对象,我们可以从这个对象中获取所有我们想要的信息

5.1获得请求url

payload = {'key1': 'value1','key2': ['value2','value3']}
r = requests.get('http://httpbin.org/get',params=payload)
print(r.url)
>>> http://httpbin.org/get?key1=value1&key2=value2&key2=value3

5.2获得响应内容

r = requests.get('https://api.github.com/events')
r.text #获得响应内容,类型为字符串
r.json() #如果 JSON 解码失败, r.json() 就会抛出一个异常
r.content #获得响应内容,类型为bytes-二进制响应内容
r.raw #原始响应内容,在罕见的情况下,你可能想获取来自服务器的原始套接字响应(后面会详细结合流数据来分析)

5.3响应状态码

r = requests.get('http://httpbin.org/get')
r.status_code

如果发送了一个错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应),我们可以通过 Response.raise_for_status() 来抛出异常:

r = requests.get('http://httpbin.org/status/404')
r.status_code
>>> 404
r.raise_for_status()
>>>
Traceback (most recent call last):
  File "requests/models.py",line 832,in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error

5.4响应头

r.headers

5.5 Response对象支持的所有方法

r.xxx #在ipython调试中,可以通过tab键来查看所有方法

该对象所有方法如下:

apparent_encoding
content
encoding
is_permanent_redirect
iter_lines
next
raw
status_code
close
cookies
headers
is_redirect
json
ok
reason
text
connection
elapsed
history
iter_content
links
raise_for_status
request
url

这里仅介绍了几个很常用的响应方法,后面遇到实际问题再展开讨论

六、超时

可以告诉 requests 在经过以 timeout 参数设定的秒数时间之后停止等待响应。基本上所有的生产代码都应该使用这一参数。如果不使用,你的程序可能会永远失去响应:

requests.get('http://github.com',timeout=0.001)

后记

以上的两种关于requests库请求方式及响应方法应该可以处理一些基本问题了,后面会继续探索requests库的其他功能。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读