Python Requests快速入门
快速上手
迫不及待了吗?本页内容为如何入门Requests提供了很好的指引。其假设你已经安装了Requests。如果还没有, 去 安装 一节看看吧。
首先,确认一下:
让我们从一些简单的示例开始吧。
发送请求
使用Requests发送网络请求非常简单。
一开始要导入Requests模块:
1 |
<span class="gp">>>> </span><span class="kn">import</span> <span class="nn">requests</span> |
然后,尝试获取某个网页。本例子中,我们来获取Github的公共时间线
1 |
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'https://github.com/timeline.json'</span><span class="p">)</span> |
现在,我们有一个名为 r 的 Response 对象。可以从这个对象中获取所有我们想要的信息。
Requests简便的API意味着所有HTTP请求类型都是显而易见的。例如,你可以这样发送一个HTTP POST请求:
1 |
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s">"http://httpbin.org/post"</span><span class="p">)</span> |
漂亮,对吧?那么其他HTTP请求类型:PUT, DELETE, HEAD以及OPTIONS又是如何的呢?都是一样的简单:
1 2 3 4 |
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="s">"http://httpbin.org/put"</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="s">"http://httpbin.org/delete"</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">head</span><span class="p">(</span><span class="s">"http://httpbin.org/get"</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">options</span><span class="p">(</span><span class="s">"http://httpbin.org/get"</span><span class="p">)</span> |
都很不错吧,但这也仅是Requests的冰山一角呢。
为URL传递参数
你也许经常想为URL的查询字符串(query string)传递某种数据。如果你是手工构建URL,那么数据会以键/值 对的形式置于URL中,跟在一个问号的后面。例如,httpbin.org/get?key=val 。 Requests允许你使用 params 关键字参数,以一个字典来提供这些参数。举例来说,如果你想传递 key1=value1 和 key2=value2 到 httpbin.org/get ,那么你可以使用如下代码:
1 2 |
<span class="gp">>>> </span><span class="n">payload</span> <span class="o">=</span> <span class="p">{</span><span class="s">'key1'</span><span class="p">:</span> <span class="s">'value1'</span><span class="p">,</span> <span class="s">'key2'</span><span class="p">:</span> <span class="s">'value2'</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">"http://httpbin.org/get"</span><span class="p">,</span> <span class="n">params</span><span class="o">=</span><span class="n">payload</span><span class="p">)</span> |
通过打印输出该URL,你能看到URL已被正确编码:
1 2 |
<span class="gp">>>> </span><span class="k">print</span> <span class="n">r</span><span class="o">.</span><span class="n">url</span> <span class="go">u'http://httpbin.org/get?key2=value2&key1=value1'</span> |
响应内容
我们能读取服务器响应的内容。再次以Github时间线为例:
1 2 3 4 |
<span class="gp">>>> </span><span class="kn">import</span> <span class="nn">requests</span> <span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'https://github.com/timeline.json'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">text</span> <span class="go">'[{"repository":{"open_issues":0,"url":"https://github.com/...</span> |
Requests会自动解码来自服务器的内容。大多数unicode字符集都能被无缝地解码。
请求发出后,Requests会基于HTTP头部对响应的编码作出有根据的推测。当你访问r.text 之时,Requests会使用其推测的文本编码。你可以找出Requests使用了什么编码,并且能够使用 r.encoding 属性来改变它:
1 2 3 |
<span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">encoding</span> <span class="go">'utf-8'</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">encoding</span> <span class="o">=</span> <span class="s">'ISO-8859-1'</span> |
如果你改变了编码,每当你访问 r.text ,Request都将会使用 r.encoding 的新值。
在你需要的情况下,Requests也可以使用定制的编码。如果你创建了自己的编码,并使用codecs 模块进行注册,你就可以轻松地使用这个解码器名称作为 r.encoding 的值, 然后由Requests来为你处理编码。
二进制响应内容
你也能以字节的方式访问请求响应体,对于非文本请求:
1 2 |
<span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">content</span> <span class="go">b'[{"repository":{"open_issues":0,"url":"https://github.com/...</span> |
Requests会自动为你解码 gzip 和 deflate 传输编码的响应数据。
例如,以请求返回的二进制数据创建一张图片,你可以使用如下代码:
1 2 3 |
<span class="gp">>>> </span><span class="kn">from</span> <span class="nn">PIL</span> <span class="kn">import</span> <span class="n">Image</span> <span class="gp">>>> </span><span class="kn">from</span> <span class="nn">StringIO</span> <span class="kn">import</span> <span class="n">StringIO</span> <span class="gp">>>> </span><span class="n">i</span> <span class="o">=</span> <span class="n">Image</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">StringIO</span><span class="p">(</span><span class="n">r</span><span class="o">.</span><span class="n">content</span><span class="p">))</span> |
JSON响应内容
Requests中也有一个内置的JSON解码器,助你处理JSON数据:
1 2 3 4 |
<span class="gp">>>> </span><span class="kn">import</span> <span class="nn">requests</span> <span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'https://github.com/timeline.json'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">json</span><span class="p">()</span> <span class="go">[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...</span> |
如果JSON解码失败, r.json 就会抛出一个异常。
原始响应内容
在罕见的情况下你可能想获取来自服务器的原始套接字响应,那么你可以访问 r.raw 。 如果你确实想这么干,那请你确保在初始请求中设置了 stream=True 。具体的你可以这么做:
1 2 3 4 5 |
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'https://github.com/timeline.json'</span><span class="p">,</span> <span class="n">stream</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">raw</span> <span class="go"><requests.packages.urllib3.response.HTTPResponse object at 0x101194810></span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">raw</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="go">'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'</span> |
定制请求头
如果你想为请求添加HTTP头部,只要简单地传递一个 dict 给 headers 参数就可以了。
例如,在前一个示例中我们没有指定content-type:
1 2 3 4 5 6 |
<span class="gp">>>> </span><span class="kn">import</span> <span class="nn">json</span> <span class="gp">>>> </span><span class="n">url</span> <span class="o">=</span> <span class="s">'https://api.github.com/some/endpoint'</span> <span class="gp">>>> </span><span class="n">payload</span> <span class="o">=</span> <span class="p">{</span><span class="s">'some'</span><span class="p">:</span> <span class="s">'data'</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">headers</span> <span class="o">=</span> <span class="p">{</span><span class="s">'content-type'</span><span class="p">:</span> <span class="s">'application/json'</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">payload</span><span class="p">),</span> <span class="n">headers</span><span class="o">=</span><span class="n">headers</span><span class="p">)</span> |
更加复杂的POST请求
通常,你想要发送一些编码为表单形式的数据—非常像一个HTML表单。 要实现这个,只需简单地传递一个字典给 data 参数。你的数据字典 在发出请求时会自动编码为表单形式:
1 2 3 4 5 6 7 8 9 10 11 |
<span class="gp">>>> </span><span class="n">payload</span> <span class="o">=</span> <span class="p">{</span><span class="s">'key1'</span><span class="p">:</span> <span class="s">'value1'</span><span class="p">,</span> <span class="s">'key2'</span><span class="p">:</span> <span class="s">'value2'</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s">"http://httpbin.org/post"</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">payload</span><span class="p">)</span> <span class="gp">>>> </span><span class="k">print</span> <span class="n">r</span><span class="o">.</span><span class="n">text</span> <span class="go">{</span> <span class="go"> ...</span> <span class="go"> "form": {</span> <span class="go"> "key2": "value2",</span> <span class="go"> "key1": "value1"</span> <span class="go"> },</span> <span class="go"> ...</span> <span class="go">}</span> |
很多时候你想要发送的数据并非编码为表单形式的。如果你传递一个 string 而不是一个dict ,那么数据会被直接发布出去。
例如,Github API v3接受编码为JSON的POST/PATCH数据:
1 2 3 4 5 |
<span class="gp">>>> </span><span class="kn">import</span> <span class="nn">json</span> <span class="gp">>>> </span><span class="n">url</span> <span class="o">=</span> <span class="s">'https://api.github.com/some/endpoint'</span> <span class="gp">>>> </span><span class="n">payload</span> <span class="o">=</span> <span class="p">{</span><span class="s">'some'</span><span class="p">:</span> <span class="s">'data'</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">payload</span><span class="p">))</span> |
POST一个多部分编码(Multipart-Encoded)的文件
Requests使得上传多部分编码文件变得很简单:
1 2 3 4 5 6 7 8 9 10 11 12 |
<span class="gp">>>> </span><span class="n">url</span> <span class="o">=</span> <span class="s">'http://httpbin.org/post'</span> <span class="gp">>>> </span><span class="n">files</span> <span class="o">=</span> <span class="p">{</span><span class="s">'file'</span><span class="p">:</span> <span class="nb">open</span><span class="p">(</span><span class="s">'report.xls'</span><span class="p">,</span> <span class="s">'rb'</span><span class="p">)}</span> <span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">files</span><span class="o">=</span><span class="n">files</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">text</span> <span class="go">{</span> <span class="go"> ...</span> <span class="go"> "files": {</span> <span class="go"> "file": "<censored...binary...data>"</span> <span class="go"> },</span> <span class="go"> ...</span> <span class="go">}</span> |
你可以显式地设置文件名:
1 2 3 4 5 6 7 8 9 10 11 12 |
<span class="gp">>>> </span><span class="n">url</span> <span class="o">=</span> <span class="s">'http://httpbin.org/post'</span> <span class="gp">>>> </span><span class="n">files</span> <span class="o">=</span> <span class="p">{</span><span class="s">'file'</span><span class="p">:</span> <span class="p">(</span><span class="s">'report.xls'</span><span class="p">,</span> <span class="nb">open</span><span class="p">(</span><span class="s">'report.xls'</span><span class="p">,</span> <span class="s">'rb'</span><span class="p">))}</span> <span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">files</span><span class="o">=</span><span class="n">files</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">text</span> <span class="go">{</span> <span class="go"> ...</span> <span class="go"> "files": {</span> <span class="go"> "file": "<censored...binary...data>"</span> <span class="go"> },</span> <span class="go"> ...</span> <span class="go">}</span> |
如果你想,你也可以发送作为文件来接收的字符串:
1 2 3 4 5 6 7 8 9 10 11 12 |
<span class="gp">>>> </span><span class="n">url</span> <span class="o">=</span> <span class="s">'http://httpbin.org/post'</span> <span class="gp">>>> </span><span class="n">files</span> <span class="o">=</span> <span class="p">{</span><span class="s">'file'</span><span class="p">:</span> <span class="p">(</span><span class="s">'report.csv'</span><span class="p">,</span> <span class="s">'some,data,to,send</span><span class="se">\n</span><span class="s">another,row,to,send</span><span class="se">\n</span><span class="s">'</span><span class="p">)}</span> <span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">files</span><span class="o">=</span><span class="n">files</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">text</span> <span class="go">{</span> <span class="go"> ...</span> <span class="go"> "files": {</span> <span class="go"> "file": "some,data,to,send\\nanother,row,to,send\\n"</span> <span class="go"> },</span> <span class="go"> ...</span> <span class="go">}</span> |
响应状态码
我们可以检测响应状态码:
1 2 3 |
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'http://httpbin.org/get'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">status_code</span> <span class="go">200</span> |
为方便引用,Requests还附带了一个内置的状态码查询对象:
1 2 |
<span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">status_code</span> <span class="o">==</span> <span class="n">requests</span><span class="o">.</span><span class="n">codes</span><span class="o">.</span><span class="n">ok</span> <span class="go">True</span> |
如果发送了一个失败请求(非200响应),我们可以通过 Response.raise_for_status() 来抛出异常:
1 2 3 4 5 6 7 8 9 |
<span class="gp">>>> </span><span class="n">bad_r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'http://httpbin.org/status/404'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">bad_r</span><span class="o">.</span><span class="n">status_code</span> <span class="go">404</span> <span class="gp">>>> </span><span class="n">bad_r</span><span class="o">.</span><span class="n">raise_for_status</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> File <span class="nb">"requests/models.py"</span>, line <span class="m">832</span>, in <span class="n">raise_for_status</span> <span class="k">raise</span> <span class="n">http_error</span> <span class="gr">requests.exceptions.HTTPError</span>: <span class="n">404 Client Error</span> |
但是,由于我们的例子中 r 的 status_code 是 200 ,当我们调用 raise_for_status() 时,得到的是:
1 2 |
<span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">raise_for_status</span><span class="p">()</span> <span class="go">None</span> |
一切都挺和谐哈。
响应头
我们可以查看以一个Python字典形式展示的服务器响应头:
1 2 3 4 5 6 7 8 9 10 11 |
<span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">headers</span> <span class="go">{</span> <span class="go"> 'status': '200 OK',</span> <span class="go"> 'content-encoding': 'gzip',</span> <span class="go"> 'transfer-encoding': 'chunked',</span> <span class="go"> 'connection': 'close',</span> <span class="go"> 'server': 'nginx/1.0.4',</span> <span class="go"> 'x-runtime': '148ms',</span> <span class="go"> 'etag': '"e1ca502697e5c9317743dc078f67693f"',</span> <span class="go"> 'content-type': 'application/json; charset=utf-8'</span> <span class="go">}</span> |
但是这个字典比较特殊:它是仅为HTTP头部而生的。根据 RFC 2616 , HTTP头部是大小写不敏感的。
因此,我们可以使用任意大写形式来访问这些响应头字段:
1 2 3 4 5 |
<span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">headers</span><span class="p">[</span><span class="s">'Content-Type'</span><span class="p">]</span> <span class="go">'application/json; charset=utf-8'</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">headers</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'content-type'</span><span class="p">)</span> <span class="go">'application/json; charset=utf-8'</span> |
如果某个响应头字段不存在,那么它的默认值为 None
1 2 |
<span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">headers</span><span class="p">[</span><span class="s">'X-Random'</span><span class="p">]</span> <span class="go">None</span> |
重定向与请求历史
使用GET或OPTIONS时,Requests会自动处理位置重定向。
Github将所有的HTTP请求重定向到HTTPS。可以使用响应对象的 history 方法来追踪重定向。 我们来看看Github做了什么:
1 2 3 4 5 6 7 |
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'http://github.com'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">url</span> <span class="go">'https://github.com/'</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">status_code</span> <span class="go">200</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">history</span> <span class="go">[<Response [301]>]</span> |
Response.history 是一个:class:Request 对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。
如果你使用的是GET或OPTIONS,那么你可以通过 allow_redirects 参数禁用重定向处理:
1 2 3 4 5 |
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'http://github.com'</span><span class="p">,</span> <span class="n">allow_redirects</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">status_code</span> <span class="go">301</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">history</span> <span class="go">[]</span> |
如果你使用的是POST,PUT,PATCH,DELETE或HEAD,你也可以启用重定向:
1 2 3 4 5 |
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s">'http://github.com'</span><span class="p">,</span> <span class="n">allow_redirects</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">url</span> <span class="go">'https://github.com/'</span> <span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">history</span> <span class="go">[<Response [301]>]</span> |
超时
你可以告诉requests在经过以 timeout 参数设定的秒数时间之后停止等待响应:
1 2 3 4 |
<span class="gp">>>> </span><span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'http://github.com'</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mf">0.001</span><span class="p">)</span> <span class="gt">Traceback (most recent call last):</span> File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span> <span class="gr">requests.exceptions.Timeout</span>: <span class="n">HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)</span> |
注:
timeout 仅对连接过程有效,与响应体的下载无关。