python爬虫学习之路(8) requests


1. 准备工作

在开始之前,请确保已经正确安装好了requests库。

2. 实例引入

urllib库中的urlopen()方法实际上是以GET方式请求网页,而requests中相应的方法就是get()方法,是不是感觉表达更明确一些?下面通过实例来看一下:

运行结果如下:

这里我们调用get()方法实现与urlopen()相同的操作,得到一个Response对象,然后分别输出了Response的类型、状态码、响应体的类型、内容以及Cookies。

通过运行结果可以发现,它的返回类型是requests.models.Response,响应体的类型是字符串str,Cookies的类型是RequestsCookieJar

使用get()方法成功实现一个GET请求,这倒不算什么,更方便之处在于其他的请求类型依然可以用一句话来完成,示例如下:

这里分别用post()put()delete()等方法实现了POST、PUT、DELETE等请求。是不是比urllib简单太多了?

其实这只是冰山一角,更多的还在后面。

3. GET请求

HTTP中最常见的请求之一就是GET请求,下面首先来详细了解一下利用requests构建GET请求的方法。

基本实例

首先,构建一个最简单的GET请求,请求的链接为http://httpbin.org/get,该网站会判断如果客户端发起的是GET请求的话,它返回相应的请求信息:

运行结果如下:

可以发现,我们成功发起了GET请求,返回结果中包含请求头、URL、IP等信息。

那么,对于GET请求,如果要附加额外的信息,一般怎样添加呢?比如现在想添加两个参数,其中namegermeyage是22。要构造这个请求链接,是不是要直接写成:

这样也可以,但是是不是有点不人性化呢?一般情况下,这种信息数据会用字典来存储。那么,怎样来构造这个链接呢?

这同样很简单,利用params这个参数就好了,示例如下:

运行结果如下:

通过运行结果可以判断,请求的链接自动被构造成了:http://httpbin.org/get?age=22&name=germey

另外,网页的返回类型实际上是str类型,但是它很特殊,是JSON格式的。所以,如果想直接解析返回结果,得到一个字典格式的话,可以直接调用json()方法。示例如下:

运行结果如下:

可以发现,调用json()方法,就可以将返回结果是JSON格式的字符串转化为字典。

但需要注意的书,如果返回结果不是JSON格式,便会出现解析错误,抛出json.decoder.JSONDecodeError异常。

抓取网页

上面的请求链接返回的是JSON形式的字符串,那么如果请求普通的网页,则肯定能获得相应的内容了。下面以“知乎”→“发现”页面为例来看一下:

这里我们加入了headers信息,其中包含了User-Agent字段信息,也就是浏览器标识信息。如果不加这个,知乎会禁止抓取。

接下来我们用到了最基础的正则表达式来匹配出所有的问题内容。关于正则表达式的相关内容,我们会在3.3节中详细介绍,这里作为实例来配合讲解。

运行结果如下:

我们发现,这里成功提取出了所有的问题内容。

抓取二进制数据

在上面的例子中,我们抓取的是知乎的一个页面,实际上它返回的是一个HTML文档。如果想抓去图片、音频、视频等文件,应该怎么办呢?

图片、音频、视频这些文件本质上都是由二进制码组成的,由于有特定的保存格式和对应的解析方式,我们才可以看到这些形形色色的多媒体。所以,想要抓取它们,就要拿到它们的二进制码。

下面以GitHub的站点图标为例来看一下:

这里抓取的内容是站点图标,也就是在浏览器每一个标签上显示的小图标,如图3-3所示。

图3-3 站点图标

这里打印了Response对象的两个属性,一个是text,另一个是content

运行结果如图3-4所示,其中前两行是r.text的结果,最后一行是r.content的结果。

图3-4 运行结果

可以注意到,前者出现了乱码,后者结果前带有一个b,这代表是bytes类型的数据。由于图片是二进制数据,所以前者在打印时转化为str类型,也就是图片直接转化为字符串,这理所当然会出现乱码。

接着,我们将刚才提取到的图片保存下来:

这里用了open()方法,它的第一个参数是文件名称,第二个参数代表以二进制写的形式打开,可以向文件里写入二进制数据。

运行结束之后,可以发现在文件夹中出现了名为favicon.ico的图标,如图3-5所示。

图3-5 图标

同样地,音频和视频文件也可以用这种方法获取。

添加headers

urllib.request一样,我们也可以通过headers参数来传递头信息。

比如,在上面“知乎”的例子中,如果不传递headers,就不能正常请求:

运行结果如下:

但如果加上headers并加上User-Agent信息,那就没问题了:

当然,我们可以在headers这个参数中任意添加其他的字段信息。

4. POST请求

前面我们了解了最基本的GET请求,另外一种比较常见的请求方式是POST。使用requests实现POST请求同样非常简单,示例如下:

这里还是请求http://httpbin.org/post,该网站可以判断如果请求是POST方式,就把相关请求信息返回。

运行结果如下:

可以发现,我们成功获得了返回结果,其中form部分就是提交的数据,这就证明POST请求成功发送了。

5. 响应

发送请求后,得到的自然就是响应。在上面的实例中,我们使用textcontent获取了响应的内容。此外,还有很多属性和方法可以用来获取其他信息,比如状态码、响应头、Cookies等。示例如下:

这里分别打印输出status_code属性得到状态码,输出headers属性得到响应头,输出cookies属性得到Cookies,输出url属性得到URL,输出history属性得到请求历史。

运行结果如下:

因为session_id过长,在此简写。可以看到,headerscookies这两个属性得到的结果分别是CaseInsensitiveDictRequestsCookieJar类型。

状态码常用来判断请求是否成功,而requests还提供了一个内置的状态码查询对象requests.codes,示例如下:

这里通过比较返回码和内置的成功的返回码,来保证请求得到了正常响应,输出成功请求的消息,否则程序终止,这里我们用requests.codes.ok得到的是成功的状态码200。

那么,肯定不能只有ok这个条件码。下面列出了返回码和相应的查询条件:

    <div id="crayon-5b4a92b6b038c438650472" class="crayon-syntax crayon-theme-github crayon-font-monaco crayon-os-pc print-yes notranslate crayon-wrapped" data-settings=" minimize scroll-mouseover wrap" style="margin-top: 12px; margin-bottom: 12px; float: left; font-size: 12px !important; line-height: 15px !important; height: auto;">

        <div class="crayon-toolbar" data-settings=" show" style="font-size: 12px !important;height: 18px !important; line-height: 18px !important;"><span class="crayon-title"></span>
        <div class="crayon-tools" style="font-size: 12px !important;height: 18px !important; line-height: 18px !important;"><div class="crayon-button crayon-nums-button crayon-pressed" title="切换是否显示行编号"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-plain-button" title="纯文本显示代码"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-wrap-button crayon-pressed" title="切换自动换行"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-expand-button" title="点击展开代码" style="display: none;"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-copy-button" title="复制代码"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-popup-button" title="在新窗口中显示代码"><div class="crayon-button-icon"></div></div></div></div>
        <div class="crayon-info" style="min-height: 16.8px !important; line-height: 16.8px !important;"></div>
        <div class="crayon-plain-wrap"><textarea class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;"># 信息性状态码

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’)








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来比对。

转载请注明:静觅 » [Python3网络爬虫开发实战] 3.2.1-基本用法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值