赵走x博客
网站访问量:151974
首页
书籍
软件
工具
古诗词
搜索
登录
Python3网络爬虫实战:46、付费讯代理、阿布云代理的使用
Python3网络爬虫实战:45、代理池的维护
Python3网络爬虫实战:44、代理的设置
Python3网络爬虫实战:43、微博宫格验证码的识别
Python3网络爬虫实战:42、点触点选验证码的识别
Python3网络爬虫实战:41、极验滑动验证码的识别
Python3网络爬虫实战:40、图形验证码的识别
Python3网络爬虫实战:38、动态渲染页面抓取:Splash的使用
Python3网络爬虫实战:37、动态渲染页面抓取:Selenium
Python3网络爬虫实战:36、分析Ajax爬取今日头条街拍美图
Python3网络爬虫实战:35、 Ajax数据爬取
Python3网络爬虫实战:34、数据存储:非关系型数据库存储:Redis
Python3网络爬虫实战:33、数据存储:非关系型数据库存储:MongoDB
Python3网络爬虫实战:32、数据存储:关系型数据库存储:MySQL
Python3网络爬虫实战:31、数据存储:文件存储
Python3网络爬虫实战:30、解析库的使用:PyQuery
Python3网络爬虫实战:29、解析库的使用:BeautifulSoup
Python3网络爬虫实战:28、解析库的使用:XPath
Python3网络爬虫实战:27、Requests与正则表达式抓取猫眼电影排行
Python3网络爬虫实战:26、正则表达式
Python3网络爬虫实战:25、requests:高级用法
Python3网络爬虫实战:24、requests:基本使用
Python3网络爬虫实战:23、使用Urllib:分析Robots协议
Python3网络爬虫实战:21、使用Urllib:处理异常
Python3网络爬虫实战:22、使用Urllib:解析链接
Python3网络爬虫实战:20、使用Urllib发送请求
Python3网络爬虫实战:19、代理基本原理
Python3网络爬虫实战:18、Session和Cookies
Python3网络爬虫实战:17、爬虫基本原理
Python3网络爬虫实战:16、Web网页基础
Python3网络爬虫实战:15、爬虫基础:HTTP基本原理
Python3网络爬虫实战:14、部署相关库的安装:Scrapyrt、Gerapy
Python3网络爬虫实战:13、部署相关库的安装:ScrapydClient、ScrapydAPI
Python3网络爬虫实战:12、部署相关库的安装:Docker、Scrapyd
Python3网络爬虫实战:11、爬虫框架的安装:ScrapySplash、ScrapyRedis
Python3网络爬虫实战:10、爬虫框架的安装:PySpider、Scrapy
Python3网络爬虫实战:9、APP爬取相关库的安装:Appium的安装
Python3网络爬虫实战:8、APP爬取相关库的安装:MitmProxy的安装
Python3网络爬虫实战:7、APP爬取相关库的安装:Charles的安装
Python3网络爬虫实战:6、Web库的安装:Flask、Tornado
Python3网络爬虫实战:5、存储库的安装:PyMySQL、PyMongo、RedisPy、RedisDump
Python3网络爬虫实战:4、数据库的安装:MySQL、MongoDB、Redis
Python3网络爬虫实战:3、解析库的安装:LXML、BeautifulSoup、PyQuery、Tesserocr
Python3网络爬虫实战:2、安装:GeckoDriver、PhantomJS、Aiohttp
Python3网络爬虫实战:1、请求库安装:Requests、Selenium、ChromeDriver
Python3网络爬虫实战:24、requests:基本使用
资源编号:75781
Python3网络爬虫实战
爬虫
热度:153
在前面一节我们了解了 Urllib 的基本用法,但是其中确实有不方便的地方。比如处理网页验证、处理 Cookies 等等,需要写 Opener、Handler 来进行处理。为了更加方便地实现这些操作,在这里就有了更为强大的库 Requests,有了它,Cookies、登录验证、代理设置等等的操作都不是事儿。
在前面一节我们了解了 Urllib 的基本用法,但是其中确实有不方便的地方。比如处理网页验证、处理 Cookies 等等,需要写 Opener、Handler 来进行处理。为了更加方便地实现这些操作,在这里就有了更为强大的库 Requests,有了它,Cookies、登录验证、代理设置等等的操作都不是事儿。 那么接下来就让我们来领略一下它的强大之处吧。 # 1 基本使用 本节我们首先来了解下 Requests 库的基本使用方法。 ## 1. 准备工作 在本节开始之前请确保已经正确安装好了 Requests 库,如果没有安装可以参考第一章的安装说明。 ## 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') ``` 运行结果如下: ```
200
{ "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" }
``` 上面的例子中我们调用 get() 方法即可实现和 urlopen() 相同的操作,得到一个 Response 对象,然后分别输出了 Response 的类型,Status Code,Response Body 的类型、内容还有 Cookies。 通过上述实例可以发现,它的返回类型是 requests.models.Response,Response Body 的类型是字符串 str,Cookies 的类型是 RequestsCookieJar。 使用了 get() 方法就成功实现了一个 GET 请求,但这倒不算什么,更方便的在于其他的请求类型依然可以用一句话来完成。 用一个实例来感受一下: ``` 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 请求的话,会返回响应的 Request 信息。 ``` 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=germey&age=22') ``` 可以是可以,但是不觉得很不人性化吗?一般的这种信息数据我们会用字典来存储,那么怎样来构造这个链接呢? 同样很简单,利用 params 这个参数就好了。 实例如下: ``` import requests data={ 'name':'mark', 'age':18 } r=requests.get('http://httpbin.org/get',params=data) print(r.text) ``` 运行结果如下: ``` { "args": { "age": "18", "name": "mark" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "python-requests/2.18.4" }, "origin": "111.197.109.238, 111.197.109.238", "url": "https://httpbin.org/get?name=mark&age=18" } ``` 通过返回信息我们可以判断,请求的链接自动被构造成了: ``` https://httpbin.org/get?name=mark&age=18 ``` 另外,网页的返回类型实际上是 str 类型,但是它很特殊,是 Json 的格式,所以如果我们想直接把返回结果解析,得到一个字典格式的话,可以直接调用 json() 方法。 用一个实例来感受一下: ``` import requests r = requests.get("http://httpbin.org/get") print(type(r.text)) print(r.json()) print(type(r.json())) ``` 运行结果如下: ```
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.18.4'}, 'origin': '111.197.109.238, 111.197.109.238', 'url': 'https://httpbin.org/get'}
``` 可以发现,调用 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(r'ExploreSpecialCard-title.*?>(.*?)<', re.S) titles=re.findall(pattern,r.text) print(titles) ``` 如上代码,我们请求了知乎-发现页面:https://www.zhihu.com/explore ,在这里加入了 Headers 信息,其中包含了 User-Agent 字段信息,也就是浏览器标识信息。如果不加这个,知乎会禁止抓取。 在接下来用到了最基础的正则表达式,来匹配出所有的问题内容,关于正则表达式会在后面的章节中详细介绍,在这里作为用到实例来配合讲解。 运行结果如下: ``` ['夏日将尽,二刷走起', '聚焦 LPL 季后赛,「3G 时代」要终结了吗?', 'Ti9 折戟沉沙,CN DOTA 出了什么问题?', '知新车 · 2019 汽车下半局'] ``` 发现成功提取出了所有的问题内容。 ### 抓取二进制数据 在上面的例子中,我们抓取的是知乎的一个页面,实际上它返回的是一个 HTML 文档,那么如果我们想抓去图片、音频、视频等文件的话应该怎么办呢? 我们都知道,图片、音频、视频这些文件都是本质上由二进制码组成的,由于有特定的保存格式和对应的解析方式,我们才可以看到这些形形色色的多媒体。所以想要抓取他们,那就需要拿到他们的二进制码。 下面我们以 GitHub 的站点图标为例来感受一下: ``` 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 所示:  图 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 的图标。 同样的,音频、视频文件也可以用这种方法获取。 ### 添加Headers 如 urllib.request 一样,我们也可以通过 headers 参数来传递头信息。 比如上面的知乎的例子,如果不传递 Headers,就不能正常请求: ``` import requests r = requests.get("https://www.zhihu.com/explore") print(r.text) ``` 运行结果如下: ```
400 Bad Request
400 Bad Request
openresty
``` 但如果加上 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 属性得到请求历史。 运行结果如下: ```
200
{'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'}
]>
http://www.baidu.com/
[] ``` 可以看到,headers 还有 cookies 这两个属性得到的结果分别是 CaseInsensitiveDict 和 RequestsCookieJar 类型。 在这里 Status Code 常用来判断请求是否成功,Requests 还提供了一个内置的 Status Code 查询对象 requests.codes。 用一个实例来感受一下: ``` import requests r = requests.get('http://www.baidu.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 请求的过程,关于更多高级的用法,会在下一节进行讲解。