python 基于aiohttp的异步爬虫实战

打印 上一主题 下一主题

主题 891|帖子 891|积分 2673

钢铁知识库,一个学习python爬虫、数据分析的知识库。人生苦短,快用python。
之前我们使用requests库爬取某个站点的时候,每发出一个请求,程序必须等待网站返回响应才能接着运行,而在整个爬虫过程中,整个爬虫程序是一直在等待的,实际上没有做任何事情。
像这种占用磁盘/内存IO、网络IO的任务,大部分时间是CPU在等待的操作,就叫IO密集型任务。对于这种情况有没有优化方案呢,当然有,那就是使用aiohttp库实现异步爬虫。
aiohttp是什么

我们在使用requests请求时,只能等一个请求先出去再回来,才会发送下一个请求。明显效率不高阿,这时候如果换成异步请求的方式,就不会有这个等待。一个请求发出去,不管这个请求什么时间响应,程序通过await挂起协程对象后直接进行下一个请求。
解决方法就是通过 aiohttp + asyncio,什么是aiohttp?一个基于 asyncio 的异步 HTTP 网络模块,可用于实现异步爬虫,速度明显快于 requests 的同步爬虫。
requests和aiohttp区别

区别就是一个同步一个是异步。话不多说直接上代码看效果。
安装aiohttp
  1. pip install aiohttp
复制代码

  • requests同步示例:
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # author: 钢铁知识库
  4. import time
  5. import requests
  6. # 同步请求
  7. def main():
  8.     start = time.time()
  9.     for i in range(5):
  10.         res = requests.get('http://httpbin.org/delay/2')
  11.         print(f'当前时间:{datetime.datetime.now()}, status_code = {res.status_code}')
  12.     print(f'requests同步耗时:{time.time() - start}')
  13.    
  14. if __name__ == '__main__':
  15.     main()
  16. '''
  17. 当前时间:2022-09-05 15:44:51.991685, status_code = 200
  18. 当前时间:2022-09-05 15:44:54.528918, status_code = 200
  19. 当前时间:2022-09-05 15:44:57.057373, status_code = 200
  20. 当前时间:2022-09-05 15:44:59.643119, status_code = 200
  21. 当前时间:2022-09-05 15:45:02.167362, status_code = 200
  22. requests同步耗时:12.785893440246582
  23. '''
复制代码
可以看到5次请求总共用12.7秒,再来看同样的请求异步多少时间。

  • aiohttp异步示例:
  1. #!/usr/bin/env python
  2. # file: day6-9同步和异步.py
  3. # author: 钢铁知识库
  4. import asyncio
  5. import time
  6. import aiohttp
  7. async def async_http():
  8.     # 声明一个支持异步的上下文管理器
  9.     async with aiohttp.ClientSession() as session:
  10.         res = await session.get('http://httpbin.org/delay/2')
  11.         print(f'当前时间:{datetime.datetime.now()}, status_code = {res.status}')
  12. tasks = [async_http() for _ in range(5)]
  13. start = time.time()
  14. # Python 3.7 及以后,不需要显式声明事件循环,可以使用 asyncio.run()来代替最后的启动操作
  15. asyncio.run(asyncio.wait(tasks))
  16. print(f'aiohttp异步耗时:{time.time() - start}')
  17. '''
  18. 当前时间:2022-09-05 15:42:32.363966, status_code = 200
  19. 当前时间:2022-09-05 15:42:32.366957, status_code = 200
  20. 当前时间:2022-09-05 15:42:32.374973, status_code = 200
  21. 当前时间:2022-09-05 15:42:32.384909, status_code = 200
  22. 当前时间:2022-09-05 15:42:32.390318, status_code = 200
  23. aiohttp异步耗时:2.5826876163482666
  24. '''
复制代码
两次对比可以看到执行过程,时间一个是顺序执行,一个是同时执行。这就是同步和异步的区别。
aiohttp使用介绍

接下来我们会详细介绍aiohttp库的用法和爬取实战。aiohttp 是一个支持异步请求的库,它和 asyncio 配合使用,可以使我们非常方便地实现异步请求操作。asyncio模块,其内部实现了对TCP、UDP、SSL协议的异步操作,但是对于HTTP请求,就需要aiohttp实现了。
aiohttp分为两部分,一部分是Client,一部分是Server。下面来说说aiohttp客户端部分的用法。
基本实例

先写一个简单的案例
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @Author  : 钢铁知识库
  4. import asyncio
  5. import aiohttp
  6. async def get_api(session, url):
  7.     # 声明一个支持异步的上下文管理器
  8.     async with session.get(url) as response:
  9.         return await response.text(), response.status
  10. async def main():
  11.     async with aiohttp.ClientSession() as session:
  12.         html, status = await get_api(session, 'http://httpbin.org/delay/2')
  13.         print(f'html: {html[:50]}')
  14.         print(f'status : {status}')
  15. if __name__ == '__main__':
  16.     #  Python 3.7 及以后,不需要显式声明事件循环,可以使用 asyncio.run(main())来代替最后的启动操作
  17.     asyncio.get_event_loop().run_until_complete(main())
  18. '''
  19. html: {
  20.   "args": {},
  21.   "data": "",
  22.   "files": {},
  23.   
  24. status : 200
  25. Process finished with exit code 0
  26. '''
复制代码
aiohttp请求的方法和之前有明显区别,主要包括如下几点:

  • 除了导入aiohttp库,还必须引入asyncio库,因为要实现异步,需要启动协程。
  • 异步的方法定义不同,前面都要统一加async来修饰。
  • with as用于声明上下文管理器,帮我们自动分配和释放资源,加上async代码支持异步。
  • 对于返回协程对象的操作,前面需要加await来修饰。response.text()返回的是协程对象。
  • 最后运行启用循环事件
注意:Python3.7及以后的版本中,可以使用asyncio.run(main())代替最后的启动操作。
URL参数设置

对于URL参数的设置,我们可以借助params设置,传入一个字典即可,实例如下:
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @Author  : 钢铁知识库
  4. import aiohttp
  5. import asyncio
  6. async def main():
  7.     params = {'name': '钢铁知识库', 'age': 23}
  8.     async with aiohttp.ClientSession() as session:
  9.         async with session.get('https://www.httpbin.org/get', params=params) as res:
  10.             print(await res.json())
  11. if __name__ == '__main__':
  12.     asyncio.get_event_loop().run_until_complete(main())
  13. '''
  14. {'args': {'age': '23', 'name': '钢铁知识库'}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'www.httpbin.org', 'User-Agent': 'Python/3.8 aiohttp/3.8.1', 'X-Amzn-Trace-Id': 'Root=1-63162e34-1acf7bde7a6d801368494c72'}, 'origin': '122.55.11.188', 'url': 'https://www.httpbin.org/get?name=钢铁知识库&age=23'}
  15. '''
复制代码
可以看到实际请求的URL后面带了后缀,这就是params的内容。
请求类型

除了get请求,aiohttp还支持其它请求类型,如POST、PUT、DELETE等,和requests使用方式类似。
  1. session.post('http://httpbin.org/post', data=b'data')
  2. session.put('http://httpbin.org/put', data=b'data')
  3. session.delete('http://httpbin.org/delete')
  4. session.head('http://httpbin.org/get')
  5. session.options('http://httpbin.org/get')
  6. session.patch('http://httpbin.org/patch', data=b'data')
复制代码
要使用这些方法,只需要把对应的方法和参数替换一下。用法和get类似就不再举例。
响应的几个方法

对于响应来说,我们可以用如下方法分别获取其中的响应情况。状态码、响应头、响应体、响应体二进制内容、响应体JSON结果,实例如下:
  1. #!/usr/bin/env python
  2. # @Author  : 钢铁知识库
  3. import aiohttp
  4. import asyncio
  5. async def main():
  6.     data = {'name': '钢铁知识库', 'age': 23}
  7.     async with aiohttp.ClientSession() as session:
  8.         async with session.post('https://www.httpbin.org/post', data=data) as response:
  9.             print('status:', response.status)  # 状态码
  10.             print('headers:', response.headers)  # 响应头
  11.             print('body:', await response.text())  # 响应体
  12.             print('bytes:', await response.read())  # 响应体二进制内容
  13.             print('json:', await response.json())  # 响应体json数据
  14. if __name__ == '__main__':
  15.     asyncio.get_event_loop().run_until_complete(main())
复制代码
  1. '''
  2. status: 200
  3. headers: <CIMultiDictProxy('Date': 'Tue, 06 Sep 2022 00:18:36 GMT', 'Content-Type': 'application/json', 'Content-Length': '534', 'Connection': 'keep-alive', 'Server': 'gunicorn/19.9.0', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true')>
  4. body: {
  5.   "args": {},
  6.   "data": "",
  7.   "files": {},
  8.   "form": {
  9.     "age": "23",
  10.     "name": "\u94a2\u94c1\u77e5\u8bc6\u5e93"
  11.   },
  12.   "headers": {
  13.     "Accept": "*/*",
  14.     "Accept-Encoding": "gzip, deflate",
  15.     "Content-Length": "57",
  16.     "Content-Type": "application/x-www-form-urlencoded",
  17.     "Host": "www.httpbin.org",
  18.     "User-Agent": "Python/3.8 aiohttp/3.8.1",
  19.     "X-Amzn-Trace-Id": "Root=1-631691dc-6aa1b2b85045a1a0481d06e1"
  20.   },
  21.   "json": null,
  22.   "origin": "122.55.11.188",
  23.   "url": "https://www.httpbin.org/post"
  24. }
  25. bytes: b'{\n  "args": {}, \n  "data": "", \n  "files": {}, \n  "form": {\n    "age": "23", \n    "name": "\\u94a2\\u94c1\\u77e5\\u8bc6\\u5e93"\n  }, \n  "headers": {\n    "Accept": "*/*", \n    "Accept-Encoding": "gzip, deflate", \n    "Content-Length": "57", \n    "Content-Type": "application/x-www-form-urlencoded", \n    "Host": "www.httpbin.org", \n    "User-Agent": "Python/3.8 aiohttp/3.8.1", \n    "X-Amzn-Trace-Id": "Root=1-631691dc-6aa1b2b85045a1a0481d06e1"\n  }, \n  "json": null, \n  "origin": "122.5.132.196", \n  "url": "https://www.httpbin.org/post"\n}\n'
  26. json: {'args': {}, 'data': '', 'files': {}, 'form': {'age': '23', 'name': '钢铁知识库'}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '57', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'www.httpbin.org', 'User-Agent': 'Python/3.8 aiohttp/3.8.1', 'X-Amzn-Trace-Id': 'Root=1-631691dc-6aa1b2b85045a1a0481d06e1'}, 'json': None, 'origin': '122.55.11.188', 'url': 'https://www.httpbin.org/post'}
  27. '''
复制代码
可以看到有些字段前面需要加await,因为其返回的是一个协程对象(如async修饰的方法),那么前面就要加await。
超时设置

我们可以借助ClientTimeout对象设置超时,例如要设置1秒的超时时间,可以这么实现:
  1. #!/usr/bin/env python
  2. # @Author  : 钢铁知识库
  3. import aiohttp
  4. import asyncio
  5. async def main():
  6.     # 设置 1 秒的超时
  7.     timeout = aiohttp.ClientTimeout(total=1)
  8.     data = {'name': '钢铁知识库', 'age': 23}
  9.     async with aiohttp.ClientSession(timeout=timeout) as session:
  10.         async with session.get('https://www.httpbin.org/delay/2', data=data) as response:
  11.             print('status:', response.status)  # 状态码
  12. if __name__ == '__main__':
  13.     asyncio.get_event_loop().run_until_complete(main())
  14. '''
  15. Traceback (most recent call last):
  16. ####中间省略####
  17.     raise asyncio.TimeoutError from None
  18. asyncio.exceptions.TimeoutError
  19. '''
复制代码
这里设置了超时1秒请求延时2秒,发现抛出异常asyncio.TimeoutError,如果正常则响应200。
并发限制

aiohttp可以支持非常高的并发量,但面对高并发网站可能会承受不住,随时有挂掉的危险,这时需要对并发进行一些控制。现在我们借助asyncio 的Semaphore来控制并发量,实例如下:
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @Author  : 钢铁知识库
  4. import asyncio
  5. from datetime import datetime
  6. import aiohttp
  7. # 声明最大并发量
  8. semaphore = asyncio.Semaphore(2)
  9. async def get_api():
  10.     async with semaphore:
  11.         print(f'scrapting...{datetime.now()}')
  12.         async with session.get('https://www.baidu.com') as response:
  13.             await asyncio.sleep(2)
  14.             # print(f'当前时间:{datetime.now()}, {response.status}')
  15. async def main():
  16.     global session
  17.     session = aiohttp.ClientSession()
  18.     tasks = [asyncio.ensure_future(get_api()) for _ in range(1000)]
  19.     await asyncio.gather(*tasks)
  20.     await session.close()
  21. if __name__ == '__main__':
  22.     asyncio.get_event_loop().run_until_complete(main())
  23. '''
  24. scrapting...2022-09-07 08:11:14.190000
  25. scrapting...2022-09-07 08:11:14.292000
  26. scrapting...2022-09-07 08:11:16.482000
  27. scrapting...2022-09-07 08:11:16.504000
  28. scrapting...2022-09-07 08:11:18.520000
  29. scrapting...2022-09-07 08:11:18.521000
  30. '''
复制代码
在main方法里,我们声明了1000个task,如果没有通过Semaphore进行并发限制,那这1000放到gather方法后会被同时执行,并发量相当大。有了信号量的控制之后,同时运行的task数量就会被控制,这样就能给aiohttp限制速度了。
aiohttp异步爬取实战

接下来我们通过异步方式练手一个小说爬虫,需求如下:
需求页面:https://dushu.baidu.com/pc/detail?gid=4308080950
目录接口:https://dushu.baidu.com/api/pc/getCatalog?data={"book_id":"4308080950"}
详情接口:https://dushu.baidu.com/api/pc/getChapterContent?data={"book_id":"4295122774","cid":"4295122774|116332"}
关键参数:book_id:小说ID、cid:章节id
采集要求:使用协程方式写入,数据存放进mongo
需求分析:点开需求页面,通过F12抓包可以发现两个接口。一个目录接口,一个详情接口。
首先第一步先请求目录接口拿到cid章节id,然后将cid传递给详情接口拿到小说数据,最后存入mongo即可。
话不多说,直接上代码:
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @Author  : 钢铁知识库
  4. # 不合适就是不合适,真正合适的,你不会有半点犹豫。
  5. import asyncio
  6. import json,re
  7. import logging
  8. import aiohttp
  9. import requests
  10. from utils.conn_db import ConnDb
  11. # 日志格式
  12. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s')
  13. # 章节目录api
  14. b_id = '4308080950'
  15. url = 'https://dushu.baidu.com/api/pc/getCatalog?data={"book_id":"'+b_id+'"}'
  16. headers = {
  17.     "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
  18.                   "Chrome/104.0.0.0 Safari/537.36"
  19. }
  20. # 并发声明
  21. semaphore = asyncio.Semaphore(5)
  22. async def download(title,b_id, cid):
  23.     data = {
  24.         "book_id": b_id,
  25.         "cid": f'{b_id}|{cid}',
  26.     }
  27.     data = json.dumps(data)
  28.     detail_url = 'https://dushu.baidu.com/api/pc/getChapterContent?data={}'.format(data)
  29.     async with semaphore:
  30.         async with aiohttp.ClientSession(headers=headers) as session:
  31.             async with session.get(detail_url) as response:
  32.                 res = await response.json()
  33.                 content = {
  34.                     'title': title,
  35.                     'content': res['data']['novel']['content']
  36.                 }
  37.                 # print(title)
  38.                 await save_data(content)
  39. async def save_data(data):
  40.     if data:
  41.         client = ConnDb().conn_motor_mongo()
  42.         db = client.baidu_novel
  43.         collection = db.novel
  44.         logging.info('saving data %s', data)
  45.         await collection.update_one(
  46.             {'title': data.get('title')},
  47.             {'$set': data},
  48.             upsert=True
  49.         )
  50. async def main():
  51.     res = requests.get(url, headers=headers)
  52.     tasks = []
  53.     for re in res.json()['data']['novel']['items']:     # 拿到某小说目录cid
  54.         title = re['title']
  55.         cid = re['cid']
  56.         tasks.append(download(title, b_id, cid))    # 将请求放到列表里,再通过gather执行并发
  57.     await asyncio.gather(*tasks)
  58. if __name__ == '__main__':
  59.     asyncio.run(main())
复制代码
至此,我们就使用aiohttp完成了对小说章节的爬取。
要实现异步处理,得先要有挂起操作,当一个任务需要等待 IO 结果的时候,可以挂起当前任务,转而去执行其他任务,这样才能充分利用好资源,要实现异步,需要了解 await 的用法,使用 await 可以将耗时等待的操作挂起,让出控制权。当协程执行的时候遇到 await,时间循环就会将本协程挂起,转而去执行别的协程,直到其他的协程挂起或执行完毕。
await 后面的对象必须是如下格式之一:

  • A native coroutine object returned from a native coroutine function,一个原生 coroutine 对象。
  • A generator-based coroutine object returned from a function decorated with types.coroutine,一个由 types.coroutine 修饰的生成器,这个生成器可以返回 coroutine 对象。
  • An object with an await method returning an iterator,一个包含 await 方法的对象返回的一个迭代器。
---- 20220909 钢铁知识库
总结

以上就是借助协程async和异步aiohttp两个主要模块完成异步爬虫的内容,
aiohttp 以异步方式爬取网站的耗时远小于 requests 同步方式,以上列举的例子希望对你有帮助。
注意,线程和协程是两个概念,后面找机会我们再聊聊进程和线程、线程和协程的关系。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

愛在花開的季節

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表