怎样用Python 写一个爬虫框架( 二 )
选择刚刚pipenv配置好的python解释器:
此时可以完整地看到项目代码:
好,环境以及源码准备完毕,接下来将结合代码讲述一个爬虫框架的编写流程
Request \u0026amp; Response Request类的目的是对aiohttp加一层封装进行模拟请求,功能如下:
封装GET、POST两种请求方式增加回调机制自定义重试次数、休眠时间、超时、重试解决方案、请求是否成功验证等功能将返回的一系列数据封装成Response类返回接下来就简单了,不过就是实现上述需求,首先,需要实现一个函数来抓取目标url,比如命名为fetch:import asyncioimport aiohttpimport async_timeoutfrom typing import Coroutineclass Request: # Default config REQUEST_CONFIG = { \u0026#39;RETRIES\u0026#39;: 3, \u0026#39;DELAY\u0026#39;: 0, \u0026#39;TIMEOUT\u0026#39;: 10, \u0026#39;RETRY_FUNC\u0026#39;: Coroutine, \u0026#39;VALID\u0026#39;: Coroutine } METHOD = def __init__(self, url, method=\u0026#39;GET\u0026#39;, request_config=None, request_session=None): self.url = url self.method = method.upper() self.request_config = request_config or self.REQUEST_CONFIG self.request_session = request_session @property def current_request_session(self): if self.request_session is None: self.request_session = aiohttp.ClientSession() self.close_request_session = True return self.request_session async def fetch(self): """Fetch all the information by using aiohttp""" if self.request_config.get(\u0026#39;DELAY\u0026#39;, 0) \u0026gt; 0: await asyncio.sleep(self.request_config) timeout = self.request_config.get(\u0026#39;TIMEOUT\u0026#39;, 10) async with async_timeout.timeout(timeout): resp = await self._make_request() try: resp_data = https://www.zhihu.com/api/v4/questions/28548989/await resp.text() except UnicodeDecodeError: resp_data = await resp.read() resp_dict = dict( rl=self.url, method=self.method, encoding=resp.get_encoding(), html=resp_data, cookies=resp.cookies, headers=resp.headers, status=resp.status, history=resp.history ) await self.request_session.close() return type(/u0026#39;Response/u0026#39;, (), resp_dict) async def _make_request(self): if self.method == /u0026#39;GET/u0026#39;: request_func = self.current_request_session.get(self.url) else: request_func = self.current_request_session.post(self.url) resp = await request_func return respif __name__ == /u0026#39;__main__/u0026#39;: loop = asyncio.get_event_loop() resp = loop.run_until_complete(Request(/u0026#39;https://docs.python-ruia.org/u0026#39;).fetch()) print(resp.status)
推荐阅读
- 聪明人养花,这3种“花”怎样也要养一盆,每年能省不少医药费
- 同比■同比增长7.1%!2021年的第一个节你花了多少钱?
- “他是我第一个会说普通话的老师”:一对师生折射青海山村蝶变
- 有必要重新开个C店吗
- 互联网怎样解决“家政服务上门速度慢”的问题
- 怎样看待从1月8号起,QQ钱包开始提现收费
- 银行it人怎样转型
- 大学再有三个月就结束了,没学到知识,参加一个软件测试培训机构好吗
- 汽车|长安UNI-K又将开创一个新的"引力"纪元?
- 汽车|冬天怎样让车内温度快速升高?座椅加热的最佳使用方式二,外循环的作用总结
