mywang88
2019-08-14
簡介
一年前開始接觸 Python 和網絡爬蟲技術。
彼時由於基礎較爲薄弱,在使用 Scrapy 框架時產生了不少疑惑。於是果斷放棄,改用 Requests 擴展庫,打算在網絡爬蟲開發的實踐中,逐步明白框架的設計意義。
期間補充了不少的 Python 語法知識,以及程序設計思想。
雖然緩慢,但也算有進步,於是決定水一貼。
基於對 Scrapy 框架的初步理解,將其進行了極大簡化,只強調核心邏輯。
代碼
from requests import Request, Session
class Engine:
@classmethod
def run(cls):
Scheduler.pool.extend(Spider().start())
while True:
req = Scheduler.pool.pop()
res = Downloader.download(req)
for p in req.callback(res):
(Pipeline, Scheduler)[isinstance(p, Request)].pool.append(p)
class Spider:
def start(self):
req = Request('GET', 'https://www.baidu.com')
req.callback = self.parse
yield req
@staticmethod
def parse(res):
item = Item()
item.html = res.text
yield item
class Scheduler:
pool = []
class Pipeline:
pool = []
class Downloader:
@classmethod
def download(cls, req):
return Session().send(req.prepare())
class Item:
pass
if __name__ == '__main__':
Engine.run()
補充
示例主要體現了 Engine 和 Spider 的邏輯,尤其是生成器(Generator)的運用。
示例忽略了包括但不限於:
- 爬蟲中間件和下載中間件等部件。
- Pipeline 的存儲功能。
- 多線程邏輯。
- Scheduler 的隊列管理邏輯。
- 各種異常的處理邏輯
- Request 類的創建(繼承或代理等封裝形式)