Python Requests

来源:互联网 发布:网络公安报警电话 编辑:程序博客网 时间:2024/05/04 00:32

发送请求

>>> import requests

然后,尝试获取某个网页

>>> r = requests.get('https://github.com/timeline.json')

现在,我们有一个名为 r 的 Response 对象。可以从这个对象中获取所有我们想要的信息。

>>>r=requests.post("http://httpbin.org/post")

>>>r=requests.put("http://httpbin.org/put")

>>> r = requests.delete("http://httpbin.org/delete")>>> r = requests.head("http://httpbin.org/get")>>> r = requests.options("http://httpbin.org/get")

为URL传递参数

httpbin.org/get?key=val 。 Requests允许你使用 params 关键字参数,以一个字典来提供这些参数。举例来说,如果你想传递 key1=value1 和 key2=value2 到 httpbin.org/get ,那么你可以使用如下代码:

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

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

>>> print r.urlu'http://httpbin.org/get?key2=value2&key1=value1'

响应内容

r.text

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

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

r.encoding
r.encoding = 'ISO-8859-1'

二进制响应内容

>>> r.contentb'[{"repository":{"open_issues":0,"url":"https://github.com/...

Requests会自动为你解码 gzip 和 deflate 传输编码的响应数据。

例如,以请求返回的二进制数据创建一张图片,你可以使用如下代码:

>>> from PIL import Image>>> from StringIO import StringIO>>> i = Image.open(StringIO(r.content))

JSON响应内容

r.json()

原始响应内容

在罕见的情况下你可能想获取来自服务器的原始套接字响应,那么你可以访问 r.raw 。 如果你确实想这么干,那请你确保在初始请求中设置了 stream=True 。具体的你可以这么做:

>>> r = requests.get('https://github.com/timeline.json', stream=True)>>> r.raw<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>>>> r.raw.read(10)'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

定制请求头

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

例如,在前一个示例中我们没有指定content-type:

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

更加复杂的POST请求

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

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

很多时候你想要发送的数据并非编码为表单形式的。如果你传递一个 string 而不是一个dict ,那么数据会被直接发布出去。

例如,Github API v3接受编码为JSON的POST/PATCH数据:

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

POST一个多部分编码(Multipart-Encoded)的文件

Requests使得上传多部分编码文件变得很简单:

>>> url = 'http://httpbin.org/post'>>> files = {'file': open('report.xls', 'rb')}>>> r = requests.post(url, files=files)>>> r.text{  ...  "files": {    "file": "<censored...binary...data>"  },  ...}

你可以显式地设置文件名:

>>> url = 'http://httpbin.org/post'>>> files = {'file': ('report.xls', open('report.xls', 'rb'))}>>> r = requests.post(url, files=files)>>> r.text{  ...  "files": {    "file": "<censored...binary...data>"  },  ...}

如果你想,你也可以发送作为文件来接收的字符串:

>>> url = 'http://httpbin.org/post'>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}>>> r = requests.post(url, files=files)>>> r.text{  ...  "files": {    "file": "some,data,to,send\\nanother,row,to,send\\n"  },  ...}

响应状态码

r.status_code200

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

>>> r.status_code == requests.codes.okTrue

如果发送了一个失败请求(非200响应),我们可以通过 Response.raise_for_status() 来抛出异常:

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

但是,由于我们的例子中 r 的 status_code 是 200 ,当我们调用 raise_for_status() 时,得到的是:

>>> r.raise_for_status()None

响应头

我们可以查看以一个Python字典形式展示的服务器响应头:

>>> r.headers{    'status': '200 OK',    'content-encoding': 'gzip',    'transfer-encoding': 'chunked',    'connection': 'close',    'server': 'nginx/1.0.4',    'x-runtime': '148ms',    'etag': '"e1ca502697e5c9317743dc078f67693f"',    'content-type': 'application/json; charset=utf-8'}

但是这个字典比较特殊:它是仅为HTTP头部而生的。根据 RFC 2616 , HTTP头部是大小写不敏感的。

因此,我们可以使用任意大写形式来访问这些响应头字段:

>>> r.headers['Content-Type']'application/json; charset=utf-8'>>> r.headers.get('content-type')'application/json; charset=utf-8'

如果某个响应头字段不存在,那么它的默认值为 None

>>> r.headers['X-Random']None

Cookies

如果某个响应中包含一些Cookie,你可以快速访问它们:

>>> url = 'http://example.com/some/cookie/setting/url'>>> r = requests.get(url)>>> r.cookies['example_cookie_name']'example_cookie_value'

要想发送你的cookies到服务器,可以使用 cookies 参数:

>>> url = 'http://httpbin.org/cookies'>>> cookies = dict(cookies_are='working')>>> r = requests.get(url, cookies=cookies)>>> r.text'{"cookies": {"cookies_are": "working"}}'

重定向与请求历史

使用GET或OPTIONS时,Requests会自动处理位置重定向。

Github将所有的HTTP请求重定向到HTTPS。可以使用响应对象的 history 方法来追踪重定向。 我们来看看Github做了什么:

>>> r = requests.get('http://github.com')>>> r.url'https://github.com/'>>> r.status_code200>>> r.history[<Response [301]>]

Response.history 是一个:class:Request 对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。

如果你使用的是GET或OPTIONS,那么你可以通过 allow_redirects 参数禁用重定向处理:

>>> r = requests.get('http://github.com', allow_redirects=False)>>> r.status_code301>>> r.history[]

如果你使用的是POST,PUT,PATCH,DELETE或HEAD,你也可以启用重定向:

>>> r = requests.post('http://github.com', allow_redirects=True)>>> r.url'https://github.com/'>>> r.history[<Response [301]>]

超时

你可以告诉requests在经过以 timeout 参数设定的秒数时间之后停止等待响应:

>>> requests.get('http://github.com', timeout=0.001)Traceback (most recent call last):  File "<stdin>", line 1, in <module>requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

注:

timeout 仅对连接过程有效,与响应体的下载无关。

错误与异常

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

遇到罕见的无效HTTP响应时,Requests则会抛出一个 HTTPError 异常。

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

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

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



0 0