1. 准备工作
在开始之前,请确保已经正确安装好了requests库。如果没有安装,可以参考1.2.1节安装。
2. 实例引入
urllib库中的urlopen()方法实际上是以GET方式请求网页,而requests中相应的方法就是get()方法,是不是感觉表达更明确一些?下面通过实例来看一下:
|
1
2
3
4
5
6
7
8
|
import requests
r = requests.get(\'https://www.baidu.com/\')
print(type(r))
print(r.status_code)
print(type(r.text))
print(r.text)
print(r.cookies)
|
运行结果如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<class \'requests.models.Response\'>
200
<class \'str\'>
<html>
<head>
<script>
location.replace(location.href.replace("https://","http://"));
</script>
</head>
<body>
<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
</body>
</html>
<RequestsCookieJar[<Cookie BIDUPSID=992C3B26F4C4D09505C5E959D5FBC005 for .baidu.com/>, <Cookie PSTM=1472227535 for .baidu.com/>, <Cookie __bsi=15304754498609545148_00_40_N_N_2_0303_C02F_N_N_N_0 for .www.baidu.com/>, <Cookie BD_NOT_HTTPS=1 for www.baidu.com/>]>
|
这里我们调用get()方法实现与urlopen()相同的操作,得到一个Response对象,然后分别输出了Response的类型、状态码、响应体的类型、内容以及Cookies。
通过运行结果可以发现,它的返回类型是requests.models.Response,响应体的类型是字符串str,Cookies的类型是RequestsCookieJar。
使用get()方法成功实现一个GET请求,这倒不算什么,更方便之处在于其他的请求类型依然可以用一句话来完成,示例如下:
|
1
2
3
4
5
|
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\')
|
这里分别用post()、put()、delete()等方法实现了POST、PUT、DELETE等请求。是不是比urllib简单太多了?
其实这只是冰山一角,更多的还在后面。
3. GET请求
HTTP中最常见的请求之一就是GET请求,下面首先来详细了解一下利用requests构建GET请求的方法。
基本实例
首先,构建一个最简单的GET请求,请求的链接为http://httpbin.org/get,该网站会判断如果客户端发起的是GET请求的话,它返回相应的请求信息:
|
1
2
3
4
|
import requests
r = requests.get(\'http://httpbin.org/get\')
print(r.text)
|
运行结果如下:
|
1
2
3
4
5
6
7
8
9
10
11
|
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.10.0"
},
"origin": "122.4.215.33",
"url": "http://httpbin.org/get"
}
|
可以发现,我们成功发起了GET请求,返回结果中包含请求头、URL、IP等信息。
那么,对于GET请求,如果要附加额外的信息,一般怎样添加呢?比如现在想添加两个参数,其中name是germey,age是22。要构造这个请求链接,是不是要直接写成:
|
1
|
r = requests.get(\'http://httpbin.org/get?name=germey&age=22\')
|
这样也可以,但是是不是有点不人性化呢?一般情况下,这种信息数据会用字典来存储。那么,怎样来构造这个链接呢?
这同样很简单,利用params这个参数就好了,示例如下:
|
1
2
3
4
5
6
7
8
|
import requests
data = {
\'name\': \'germey\',
\'age\': 22
}
r = requests.get("http://httpbin.org/get", params=data)
print(r.text)
|
运行结果如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
{
"args": {
"age": "22",
"name": "germey"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.10.0"
},
"origin": "122.4.215.33",
"url": "http://httpbin.org/get?age=22&name=germey"
}
|
通过运行结果可以判断,请求的链接自动被构造成了:http://httpbin.org/get?age=22&name=germey。
另外,网页的返回类型实际上是str类型,但是它很特殊,是JSON格式的。所以,如果想直接解析返回结果,得到一个字典格式的话,可以直接调用json()方法。示例如下:
|
1
2
3
4
5
6
|
import requests
r = requests.get("http://httpbin.org/get")
print(type(r.text))
print(r.json())
print(type(r.json()))
|
运行结果如下:
|
1
2
3
|
<class \'str\'>
{\'headers\': {\'Accept-Encoding\': \'gzip, deflate\', \'Accept\': \'*/*\', \'Host\': \'httpbin.org\', \'User-Agent\': \'python-requests/2.10.0\'}, \'url\': \'http://httpbin.org/get\', \'args\': {}, \'origin\': \'182.33.248.131\'}
<class \'dict\'>
|
可以发现,调用json()方法,就可以将返回结果是JSON格式的字符串转化为字典。
但需要注意的书,如果返回结果不是JSON格式,便会出现解析错误,抛出json.decoder.JSONDecodeError异常。
抓取网页
上面的请求链接返回的是JSON形式的字符串,那么如果请求普通的网页,则肯定能获得相应的内容了。下面以“知乎”→“发现”页面为例来看一下:
|
1
2
3
4
5
6
7
8
9
10
|
import requests
import re
headers = {
\'User-Agent\': \'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36\'
}
r = requests.get("https://www.zhihu.com/explore", headers=headers)
pattern = re.compile(\'explore-feed.*?question_link.*?>(.*?)</a>\', re.S)
titles = re.findall(pattern, r.text)
print(titles)
|
这里我们加入了headers信息,其中包含了User-Agent字段信息,也就是浏览器标识信息。如果不加这个,知乎会禁止抓取。
接下来我们用到了最基础的正则表达式来匹配出所有的问题内容。关于正则表达式的相关内容,我们会在3.3节中详细介绍,这里作为实例来配合讲解。
运行结果如下:
|
1
|
[\'\n为什么很多人喜欢提及「拉丁语系」这个词?\n\', \'\n在没有水的情况下水系宝可梦如何战斗?\n\', \'\n有哪些经验可以送给 Kindle 新人?\n\', \'\n谷歌的广告业务是如何赚钱的?\n\', \'\n程序员该学习什么,能在上学期间挣钱?\n\', \'\n有哪些原本只是一个小消息,但回看发现是个惊天大新闻的例子?\n\', \'\n如何评价今敏?\n\', \'\n源氏是怎么把那么长的刀从背后拔出来的?\n\', \'\n年轻时得了绝症或大病是怎样的感受?\n\', \'\n年轻时得了绝症或大病是怎样的感受?\n\']
|
我们发现,这里成功提取出了所有的问题内容。
抓取二进制数据
在上面的例子中,我们抓取的是知乎的一个页面,实际上它返回的是一个HTML文档。如果想抓去图片、音频、视频等文件,应该怎么办呢?
图片、音频、视频这些文件本质上都是由二进制码组成的,由于有特定的保存格式和对应的解析方式,我们才可以看到这些形形色色的多媒体。所以,想要抓取它们,就要拿到它们的二进制码。
下面以GitHub的站点图标为例来看一下:
|
1
2
3
4
5
|
import requests
r = requests.get("https://github.com/favicon.ico")
print(r.text)
print(r.content)
|
这里抓取的内容是站点图标,也就是在浏览器每一个标签上显示的小图标,如图3-3所示。
图3-3 站点图标
这里打印了Response对象的两个属性,一个是text,另一个是content。
运行结果如图3-4所示,其中前两行是r.text的结果,最后一行是r.content的结果。
图3-4 运行结果
可以注意到,前者出现了乱码,后者结果前带有一个b,这代表是bytes类型的数据。由于图片是二进制数据,所以前者在打印时转化为str类型,也就是图片直接转化为字符串,这理所当然会出现乱码。
接着,我们将刚才提取到的图片保存下来:
|
1
2
3
4
5
|
import requests
r = requests.get("https://github.com/favicon.ico")
with open(\'favicon.ico\', \'wb\') as f:
f.write(r.content)
|
这里用了open()方法,它的第一个参数是文件名称,第二个参数代表以二进制写的形式打开,可以向文件里写入二进制数据。
运行结束之后,可以发现在文件夹中出现了名为favicon.ico的图标,如图3-5所示。
同样地,音频和视频文件也可以用这种方法获取。
添加headers
与urllib.request一样,我们也可以通过headers参数来传递头信息。
比如,在上面“知乎”的例子中,如果不传递headers,就不能正常请求:
|
1
2
3
4
|
import requests
r = requests.get("https://www.zhihu.com/explore")
print(r.text)
|
运行结果如下:
|
1
2
3
|
<html><body><h1>500 Server Error</h1>
An internal server error occured.
</body></html>
|
但如果加上headers并加上User-Agent信息,那就没问题了:
|
1
2
3
4
5
6
7
|
import requests
headers = {
\'User-Agent\': \'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36\'
}
r = requests.get("https://www.zhihu.com/explore", headers=headers)
print(r.text)
|
当然,我们可以在headers这个参数中任意添加其他的字段信息。
4. POST请求
前面我们了解了最基本的GET请求,另外一种比较常见的请求方式是POST。使用requests实现POST请求同样非常简单,示例如下:
|
1
2
3
4
5
|
import requests
data = {\'name\': \'germey\', \'age\': \'22\'}
r = requests.post("http://httpbin.org/post", data=data)
print(r.text)
|
这里还是请求http://httpbin.org/post,该网站可以判断如果请求是POST方式,就把相关请求信息返回。
运行结果如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
{
"args": {},
"data": "",
"files": {},
"form": {
"age": "22",
"name": "germey"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "18",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.10.0"
},
"json": null,
"origin": "182.33.248.131",
"url": "http://httpbin.org/post"
}
|
可以发现,我们成功获得了返回结果,其中form部分就是提交的数据,这就证明POST请求成功发送了。
5. 响应
发送请求后,得到的自然就是响应。在上面的实例中,我们使用text和content获取了响应的内容。此外,还有很多属性和方法可以用来获取其他信息,比如状态码、响应头、Cookies等。示例如下:
|
1
2
3
4
5
6
7
8
|
import requests
r = requests.get(\'http://www.jianshu.com\')
print(type(r.status_code), r.status_code)
print(type(r.headers), r.headers)
print(type(r.cookies), r.cookies)
print(type(r.url), r.url)
print(type(r.history), r.history)
|
这里分别打印输出status_code属性得到状态码,输出headers属性得到响应头,输出cookies属性得到Cookies,输出url属性得到URL,输出history属性得到请求历史。
运行结果如下:
|
1
2
3
4
5
|
<class \'int\'> 200
<class \'requests.structures.CaseInsensitiveDict\'> {\'X-Runtime\': \'0.006363\', \'Connection\': \'keep-alive\', \'Content-Type\': \'text/html; charset=utf-8\', \'X-Content-Type-Options\': \'nosniff\', \'Date\': \'Sat, 27 Aug 2016 17:18:51 GMT\', \'Server\': \'nginx\', \'X-Frame-Options\': \'DENY\', \'Content-Encoding\': \'gzip\', \'Vary\': \'Accept-Encoding\', \'ETag\': \'W/"3abda885e0e123bfde06d9b61e696159"\', \'X-XSS-Protection\': \'1; mode=block\', \'X-Request-Id\': \'a8a3c4d5-f660-422f-8df9-49719dd9b5d4\', \'Transfer-Encoding\': \'chunked\', \'Set-Cookie\': \'read_mode=day; path=/, default_font=font2; path=/, _session_id=xxx; path=/; HttpOnly\', \'Cache-Control\': \'max-age=0, private, must-revalidate\'}
<class \'requests.cookies.RequestsCookieJar\'> <RequestsCookieJar[<Cookie _session_id=xxx for www.jianshu.com/>, <Cookie default_font=font2 for www.jianshu.com/>, <Cookie read_mode=day for www.jianshu.com/>]>
<class \'str\'> http://www.jianshu.com/
<class \'list\'> []
|
因为session_id过长,在此简写。可以看到,headers和cookies这两个属性得到的结果分别是CaseInsensitiveDict和RequestsCookieJar类型。
状态码常用来判断请求是否成功,而requests还提供了一个内置的状态码查询对象requests.codes,示例如下:
|
1
2
3
4
|
import requests
r = requests.get(\'http://www.jianshu.com\')
exit() if not r.status_code == requests.codes.ok else print(\'Request Successfully\')
|
这里通过比较返回码和内置的成功的返回码,来保证请求得到了正常响应,输出成功请求的消息,否则程序终止,这里我们用requests.codes.ok得到的是成功的状态码200。
那么,肯定不能只有ok这个条件码。下面列出了返回码和相应的查询条件:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
# 信息性状态码
100: (\'continue\',),
101: (\'switching_protocols\',),
102: (\'processing\',),
103: (\'checkpoint\',),
122: (\'uri_too_long\', \'request_uri_too_long\'),
# 成功状态码
200: (\'ok\', \'okay\', \'all_ok\', \'all_okay\', \'all_good\', \'\\o/\', \'✓\'),
201: (\'created\',),
202: (\'accepted\',),
203: (\'non_authoritative_info\', \'non_authoritative_information\'),
204: (\'no_content\',),
205: (\'reset_content\', \'reset\'),
206: (\'partial_content\', \'partial\'),
207: (\'multi_status\', \'multiple_status\', \'multi_stati\', \'multiple_stati\'),
208: (\'already_reported\',),
226: (\'im_used\',),
# 重定向状态码
300: (\'multiple_choices\',),
301: (\'moved_permanently\', \'moved\', \'\\o-\'),
302: (\'found\',),
303: (\'see_other\', \'other\'),
304: (\'not_modified\',),
305: (\'use_proxy\',),
306: (\'switch_proxy\',),
307: (\'temporary_redirect\', \'temporary_moved\', \'temporary\'),
308: (\'permanent_redirect\',
\'resume_incomplete\', \'resume\',), # These 2 to be removed in 3.0
# 客户端错误状态码
400: (\'bad_request\', \'bad\'),
401: (\'unauthorized\',),
402: (\'payment_required\', \'payment\'),
403: (\'forbidden\',),
404: (\'not_found\', \'-o-\'),
405: (\'method_not_allowed\', \'not_allowed\'),
406: (\'not_acceptable\',),
407: (\'proxy_authentication_required\', \'proxy_auth\', \'proxy_authentication\'),
408: (\'request_timeout\', \'timeout\'),
409: (\'conflict\',),
410: (\'gone\',),
411: (\'length_required\',),
412: (\'precondition_failed\', \'precondition\'),
413: (\'request_entity_too_large\',),
414: (\'request_uri_too_large\',),
415: (\'unsupported_media_type\', \'unsupported_media\', \'media_type\'),
416: (\'requested_range_not_satisfiable\', \'requested_range\', \'range_not_satisfiable\'),
417: (\'expectation_failed\',),
418: (\'im_a_teapot\', \'teapot\', \'i_am_a_teapot\'),
421: (\'misdirected_request\',),
422: (\'unprocessable_entity\', \'unprocessable\'),
423: (\'locked\',),
424: (\'failed_dependency\', \'dependency\'),
425: (\'unordered_collection\', \'unordered\'),
426: (\'upgrade_required\', \'upgrade\'),
428: (\'precondition_required\', \'precondition\'),
429: (\'too_many_requests\', \'too_many\'),
431: (\'header_fields_too_large\', \'fields_too_large\'),
444: (\'no_response\', \'none\'),
449: (\'retry_with\', \'retry\'),
450: (\'blocked_by_windows_parental_controls\', \'parental_controls\'),
451: (\'unavailable_for_legal_reasons\', \'legal_reasons\'),
499: (\'client_closed_request\',),
# 服务端错误状态码
500: (\'internal_server_error\', \'server_error\', \'/o\\\', \'✗\'),
501: (\'not_implemented\',),
502: (\'bad_gateway\',),
503: (\'service_unavailable\', \'unavailable\'),
504: (\'gateway_timeout\',),
505: (\'http_version_not_supported\', \'http_version\'),
506: (\'variant_also_negotiates\',),
507: (\'insufficient_storage\',),
509: (\'bandwidth_limit_exceeded\', \'bandwidth\'),
510: (\'not_extended\',),
511: (\'network_authentication_required\', \'network_auth\', \'network_authentication\')
|
比如,如果想判断结果是不是404状态,可以用requests.codes.not_found来比对。