【python】使用 Requests 发送网络请求

安装 Requests

使用命令安装requests

$ pip install requests
发送请求

使用Requests发送请求要先导入Requests

>>> import requests

发送HTTP请求

>>> response = requests.get('https://api.github.com/events')
>>> response = requests.post('https://api.github.com/events')
>>> response = requests.put('https://api.github.com/events')
>>> response = requests.delete('https://api.github.com/events')
>>> response = requests.head('https://api.github.com/events')
>>> response = requests.options('https://api.github.com/events')

返回值 response 是一个 Response 对象,我们可以从这个对象中获取所有我们想要的信息。

传递参数

请求传参时可以直接传入一个字典

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> response = requests.get("http://www.baidu.com", params=payload)

通过打印输出该 URL,你能看到 URL 已被正确编码:

>>> print(response.url)
http://www.baidu.com?key2=value2&key1=value1

字典里值为 None 的键都不会被添加到 URL 的查询字符串里。

你还可以将一个列表作为值传入:

>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}

>>> response = requests.get('http://www.baidu.com', params=payload)
>>> print(response.url)
http://www.baidu.com?key1=value1&key2=value2&key2=value3

在表单中多个元素使用同一 key 的时候,可以为 data 参数传入一个元组列表

>>> payload = (('key1', 'value1'), ('key1', 'value2'))
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
  ...
  "form": {
    "key1": [
      "value1",
      "value2"
    ]
  },
  ...
}
定制请求头

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

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

>>> response = requests.get(url, headers=headers)

注意: 所有的 header 值必须是 string、bytestring 或者 unicode。尽管传递 unicode header 也是允许的,但不建议这样做。

响应内容

我们能读取服务器响应的内容

>>> response.text
>>> response.content.decode()

Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。

请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 response.text 之时,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用 r.encoding 属性来改变它:

>>> response.encoding
'utf-8'
>>> response.encoding = 'ISO-8859-1'
JSON 响应内容

Requests 中也有一个内置的 JSON 解码器,助你处理 JSON 数据:

>>> response = requests.get('https://api.github.com/events')
>>> response.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

如果 JSON 解码失败, response.json() 就会抛出一个异常。例如,响应内容是 401 (Unauthorized),尝试访问 response.json() 将会抛出 ValueError: No JSON object could be decoded 异常。

需要注意的是,成功调用 response.json() 并意味着响应的成功。有的服务器会在失败的响应中包含一个 JSON 对象(比如 HTTP 500 的错误细节)。这种 JSON 会被解码返回。要检查请求是否成功,请使用 response.raise_for_status() 或者检查 response.status_code 是否和你的期望相同。

响应状态码

我们可以检测响应状态码:

>>> response = requests.get('http://httpbin.org/get')
>>> response.status_code
200

为方便引用,Requests还附带了一个内置的状态码查询对象:

>>> response.status_code == requests.codes.ok
True

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

>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r.status_code
404

>>> bad_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
错误与异常

遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个 ConnectionError 异常。

如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError 异常。

若请求超时,则抛出一个 Timeout 异常。

若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。

所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。


想要了解更多内容,请参见网址:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值