目录
前言
前面我们学习了urllib的基础使用方法。不过,urllib在实际应用中存在一些不便之处。以网页验证和Cookies处理为例,使用 urllib 时,得编写Opener和Handler才能完成操作。
为了更轻松地实现这些操作,功能更强大的 requests 库应运而生。利用 requests 库,管理Cookies、进行登录验证,以及设置代理等操作,都能轻松搞定。下面,我们先介绍 requests 库的基本使用方法。
一、准备工作
在开始使用requests库前,要确保已经正确安装了该库。如果还未安装,可以通过下面命令安装:
- 对于 Python 2:
pip install requests
- 对于 Python 3(推荐):
pip3 install requests
二、实例引入
urllib库用urlopen()方法发起GET方式的网页请求。与之对应,requests库提供了get()方法。相比之下,get()这个名字,能让人更直接地明白它用于发起GET请求。
下面通过实例来看:
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)
运行结果如下:
<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 bs=153047544986095451480040NN20303CO2FNNNO for .www.baidu.com/>,<Cookie BD_NOT_HTTPS=1 for www.baidu.com/>]>
在这儿,我们通过调用requests库的get()方法,完成了和urllib库中urlopen()一样的操作,得到一个Response对象。紧接着,我们又输出了这个Response对象的类型、状态码,响应体的类型、内容,以及Cookies信息。从运行结果能知道,Response对象的类型是requests.models.Response,响应体是str字符串类型,Cookies是RequestsCookieJar类型。
用get()方法实现GET请求并不稀奇,requests库更方便的地方在于,用一句话就能实现POST、PUT等其他类型的请求 ,示例如下:
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')
requests.options('http://httpbin.org/get')
这里分别用post()、put()、delete()等方法实现了POST、PUT、DELETE等请求。相比urllib,是不是简单很多?这其实只是requests库强大功能的一小部分。
三、GET请求
GET请求是HTTP协议里特别常见的一种请求方式。接下来,咱们就深入了解一下,怎么用requests库来发起GET请求。
3.1 基本示例
第一步,搭建一个最为简单的GET请求,请求的目标链接是http://httpbin.org/get。这个网站能识别客户端发起的请求类型,要是检测到是GET请求,就会把对应的请求信息返回过来。
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请求,返回内容里有请求头、URL、IP等信息。那么,当发起GET请求,需要添加额外信息时,通常该怎么做呢?举个例子,现在要添加两个参数,一个是name,值为germey,另一个是age,值为22 。
要构造这个请求链接,是不是直接写成:
r = requests.get('http://httpbin.org/get?name=germey&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&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异常。
3.2 抓取网页
上面请求的链接,返回内容是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.*?>(.*?)</a>', re.S)
titles = re.findall(pattern, r.text)
print(titles)
这里,我们在请求中添加了headers信息,里面有User - Agent字段,这个字段用来标识浏览器。要是不加上这一项,知乎就不让我们抓取页面内容。之后,我们用最基础的正则表达式,把页面上所有问题内容匹配出来了。正则表达式的知识,我们会在后面深入讲解,这里先借助这个实例,给大家做个初步介绍 。
运行结果如下:
['\n为什么很多人喜欢提及「拉丁语系」这个词?\n', '\n在没有水的情况下水系宝可梦如何战斗?\n', '\n有哪些经验可以送给 Kindle 新人?\n', '\n谷歌的广告业务是如何赚钱的?\n', "\n程序员该学习什么,能在上学期间挣钱?\n", '\n有哪些原本只是一个小消息,但回看发现是个惊天大新闻的例子?\n', "\n如何评价今敏?\n", '\n源氏是怎么把那么长的刀从背后拔出来的?\n', "\n年轻时得了绝症或大病是怎样的感受?\n", "\n年轻时得了绝症或大病是怎样的感受?\n"]
我们发现,这里成功提取出了所有的问题内容。
3.3 抓取二进制数据
上面例子里,我们抓取了知乎的一个页面,得到的是HTML文档。那要是想抓取图片、音频、视频这类文件,该怎么做呢?图片、音频、视频这些文件,本质都是二进制码。因为它们有特定保存格式,配合对应的解析方法,我们才能看到这些丰富多彩的多媒体内容。所以,要抓取这些文件,就得获取它们的二进制码 。
下面以GitHub的站点图标为例来看:
import requests
r = requests.get("https://github.com/favicon.ico")
print(r.text)
print(r.content)
这次抓取的是站点图标,就是浏览器每个标签上显示的小图标。我们打印了Response对象的text和content这两个属性。运行程序后,前两行显示的是r.text的结果,最后一行是r.content的结果。能看到,r.text结果出现乱码,r.content结果前面有个b,这表明它是bytes类型数据。因为图片属于二进制数据,r.text打印时会把图片数据转成str类型,相当于直接将图片转为字符串,乱码也就不可避免了。
接着,我们将刚才提取到的图片保存下来:
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.4 添加headers
和urllib.request一样,requests也能借助headers参数来传递请求头信息。就拿上面抓取知乎页面的例子来说,如果不设置headers参数传递请求头信息,就无法正常发起请求。
import requests
r = requests.get("https://www.zhihu.com/explore")
print(r.text)
运行结果如下:
<html><body><h1>500 Server Error</h1>An internal server error occured.</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这个参数中任意添加其他的字段信息。
四、POST请求
前面,我们认识了最基础的GET请求。在HTTP请求里,还有一种常见的请求方式,那就是POST请求。用requests库实现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请求成功发送出去了。
五、响应
发送请求之后,肯定会得到响应结果。就像上面的例子,我们通过text和content属性,获取到了响应内容。其实,除了这两种,借助其他属性和方法,还能获取更多信息,像状态码、响应头,以及Cookies等内容。
示例如下:
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属性,就能看到请求历史记录。
运行结果如下:
<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/"3abda885e0e123bfde06dgb61e696159"', 'X-XSS-Protection': '1;mode-block', 'X-Request-Id': 'a8a3c4d5-f660-422f-8df9-49719ddgb5d4', '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属性获取到的数据类型是CaseInsensitiveDict,通过cookies属性获取到的数据类型则是RequestsCookieJar。
在判断请求是否成功时,状态码是常用的依据。requests库还内置了一个状态码查询对象,叫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库内置的成功返回码作比较。要是二者匹配,就说明请求正常响应,程序会输出成功请求的消息;要是不匹配,程序就会终止。这里,我们用requests.codes.ok获取到的成功状态码为200。
当然,requests.codes里可不只有ok这一个条件码。下面,给大家列出各类返回码以及对应的查询条件。
# 信息性状态码
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',),
# 客户端错误状态码
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-0-'),
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', 'client_closed_request'),
# 服务端错误状态码
500: ('internal_server_error','server_error', '/o\\', 'X'),
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`去做对比。