Python3网络爬虫实战---2四、requests:基本使用

上一篇文章: Python3网络爬虫实战---2三、使用Urllib:分析Robots协议
下一篇文章:

在前面一节咱们了解了 Urllib 的基本用法,可是其中确实有不方便的地方。好比处理网页验证、处理 Cookies 等等,须要写 Opener、Handler 来进行处理。为了更加方便地实现这些操做,在这里就有了更为强大的库 Requests,有了它,Cookies、登陆验证、代理设置等等的操做都不是事儿。html

那么接下来就让咱们来领略一下它的强大之处吧。python

1 基本使用

本节咱们首先来了解下 Requests 库的基本使用方法。git

1. 准备工做

在本节开始以前请确保已经正确安装好了 Requests 库,若是没有安装能够参考第一章的安装说明。github

2. 实例引入

在 Urllib 库中有 urlopen() 的方法,实际上它是以 GET 方式请求了一个网页。
那么在 Requests 中,相应的方法就是 get() 方法,是否是感受表达更明确一些?
下面咱们用一个实例来感觉一下:正则表达式

import requests
r=requests.get('http://httpbin.org/get')
print(type(r),r.status_code,type(r.text),r.text,type(r.cookies),r.cookies,sep='\n')

运行结果以下:json

<class 'requests.models.Response'>
200
<class 'str'>
{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.21.0"
  }, 
  "origin": "114.253.118.8, 114.253.118.8", 
  "url": "https://httpbin.org/get"
}

<class 'requests.cookies.RequestsCookieJar'>
<RequestsCookieJar[]>

上面的例子中咱们调用 get() 方法便可实现和 urlopen() 相同的操做,获得一个 Response 对象,而后分别输出了 Response 的类型,Status Code,Response Body 的类型、内容还有 Cookies。
经过上述实例能够发现,它的返回类型是 requests.models.Response,Response Body 的类型是字符串 str,Cookies 的类型是 RequestsCookieJar。
使用了 get() 方法就成功实现了一个 GET 请求,但这倒不算什么,更方便的在于其余的请求类型依然能够用一句话来完成。
用一个实例来感觉一下:segmentfault

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 简单太多了?
其实这只是冰山一角,更多的还在后面。windows

3. GET请求

HTTP 中最多见的请求之一就是 GET 请求,咱们首先来详细了解下利用 Requests 来构建 GET 请求的方法以及相关属性方法操做。浏览器

基本实例

首先让咱们来构建一个最简单的 GET 请求,请求的连接为:http://httpbin.org/get,它会判断若是若是是 GET 请求的话,会返回响应的 Request 信息。cookie

import requests

r = requests.get('http://httpbin.org/get')
print(r.text)
运行结果以下:
{
  "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 请求,返回的结果中包含了 Request Headers、URL、IP 等信息。
那么 GET 请求,若是要附加额外的信息通常是怎样来添加?好比如今我想添加两个参数,名字 name 是 germey,年龄 age 是 22。构造这个请求连接是否是咱们要直接写成:
r = requests.get('http://httpbin.org/get?name=g...;age=22')
能够是能够,可是不以为很不人性化吗?通常的这种信息数据咱们会用字典来存储,那么怎样来构造这个连接呢?
一样很简单,利用 params 这个参数就行了。
实例以下:

import requests

data = {
    'name': 'germey',
    'age': 22
}
r = requests.get("http://httpbin.org/get", params=data)
print(r.text)

运行结果以下:

{
  "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&amp;name=germey"
}

经过返回信息咱们能够判断,请求的连接自动被构形成了:http://httpbin.org/get?age=22...;name=germey。
另外,网页的返回类型其实是 str 类型,可是它很特殊,是 Json 的格式,因此若是咱们想直接把返回结果解析,获得一个字典格式的话,能够直接调用 json() 方法。
用一个实例来感觉一下:

import requests

r = requests.get("http://httpbin.org/get")
print(type(r.text))
print(r.json())
print(type(r.json()))

运行结果以下:
<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 形式的字符串,那么若是咱们请求普通的网页,那么确定就能得到相应的内容了。
下面咱们以知乎-发现页面为例来感觉一下:

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.*?&gt;(.*?)&lt;/a&gt;', re.S)
titles = re.findall(pattern, r.text)
print(titles)

如上代码,咱们请求了知乎-发现页面:https://www.zhihu.com/explore,在这里加入了 Headers 信息,其中包含了 User-Agent 字段信息,也就是浏览器标识信息。若是不加这个,知乎会禁止抓取。
在接下来用到了最基础的正则表达式,来匹配出全部的问题内容,关于正则表达式会在后面的章节中详细介绍,在这里做为用到实例来配合讲解。
运行结果以下:

['\n如何评价杨超越对偶像意义的理解?\n', '\n中国绿发会宣称「穿山甲功能性灭绝」,引起学者质疑后反控对方诽谤,应该相信哪边?\n', '\n如何科学地解释MacBook Pro 2019的CPU性能表现接近甚至超过ROG玩家国度枪神3?\n', '\n如何评价杨超越对偶像意义的理解?\n', '\n盛京剑客为啥退出知乎了?\n', '\n怎么看我国跆拳道选手郑姝音被判负后众人不满,我国参加相似比赛还有必要么?\n', '\n你为何这么不肯意《极限挑战》换人?\n', '\n「吉卜力工做室」是一家怎样的动画制做公司?\n', '\n你为何不喜欢张雪迎?\n', '\n《王者荣耀》中,你遇到哪些有意思的队友?\n']

发现成功提取出了全部的问题内容。

抓取二进制数据

在上面的例子中,咱们抓取的是知乎的一个页面,实际上它返回的是一个 HTML 文档,那么若是咱们想抓去图片、音频、视频等文件的话应该怎么办呢?
咱们都知道,图片、音频、视频这些文件都是本质上由二进制码组成的,因为有特定的保存格式和对应的解析方式,咱们才能够看到这些形形色色的多媒体。因此想要抓取他们,那就须要拿到他们的二进制码。
下面咱们以 GitHub 的站点图标为例来感觉一下:

import requests

r = requests.get("https://github.com/favicon.ico")
print(r.text)
print(r.content)

抓取的内容是站点图标,也就是在浏览器每个标签上显示的小图标,如图 3-3 所示:
clipboard.png
图 3-3 站点图标
在这里打印了 Response 对象的两个属性,一个是text,另外一个是 content。
运行结果以下,因为包含特殊内容,在此放运行结果的图片,如图 3-4 所示:

clipboard.png

图 3-4 运行结果
那么前两行即是 r.text 的结果,最后一行是 r.content 的结果。
能够注意到,前者出现了乱码,后者结果前面带有一个 b,表明这是 bytes 类型的数据。因为图片是二进制数据,因此前者在打印时转化为 str 类型,也就是图片直接转化为字符串,理所固然会出现乱码。
两个属性有什么区别?前者返回的是字符串类型,若是返回结果是文本文件,那么用这种方式直接获取其内容便可。若是返回结果是图片、音频、视频等文件,Requests 会为咱们自动解码成 bytes 类型,即获取字节流数据。
进一步地,咱们能够将刚才提取到的图片保存下来。

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所示:

clipboard.png

图 3-5 图标
一样的,音频、视频文件也能够用这种方法获取。

添加Headers

如 urllib.request 同样,咱们也能够经过 headers 参数来传递头信息。
好比上面的知乎的例子,若是不传递 Headers,就不能正常请求:

import requests

r = requests.get("https://www.zhihu.com/explore")
print(r.text)

运行结果以下:

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>openresty</center>
</body>
</html>

但若是加上 Headers 中加上 User-Agent 信息,那就没问题了:

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 了,就像模拟表单提交同样,将一些数据提交到某个连接。
使用 Request 是实现 POST 请求一样很是简单。
咱们先用一个实例来感觉一下:

import requests

data = {'name': 'germey', 'age': '22'}
r = requests.post("http://httpbin.org/post", data=data)
print(r.text)

这里咱们仍是请求:http://httpbin.org/post,它能够判断若是请求是 POST 方式,就把相关请求信息输出出来。
运行结果以下:

{
  "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. Response

发送 Request 以后,获得的天然就是 Response,在上面的实例中咱们使用了 text 和 content 获取了 Response 内容,不过还有不少属性和方法能够获取其余的信息,好比状态码 Status Code、Headers、Cookies 等信息。
下面用一个实例来感觉一下:

import requests

r = requests.get('http://www.baidu.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 属性获得 Response Headers,cookies 属性获得 Cookies,url 属性获得 URL,history 属性获得请求历史。
运行结果以下:

<class 'int'> 200
<class 'requests.structures.CaseInsensitiveDict'> {'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'Keep-Alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Mon, 17 Jun 2019 11:01:04 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:27:32 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}
<class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
<class 'str'> http://www.baidu.com/
<class 'list'> []

能够看到,headers 还有 cookies 这两个属性获得的结果分别是 CaseInsensitiveDict 和 RequestsCookieJar 类型。
在这里 Status Code 经常使用来判断请求是否成功,Requests 还提供了一个内置的 Status Code 查询对象 requests.codes。
用一个实例来感觉一下:

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 这个条件码,下面列出了返回码和相应的查询条件:

# Informational.
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',),

# Redirection.
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

# Client Error.
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',),

# Server Error.
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 来比对。

6. 结语

本节咱们了解了利用 Requests 模拟最基本的 GET 和 POST 请求的过程,关于更多高级的用法,会在下一节进行讲解。

相关文章
相关标签/搜索