Asyncpy是我基于asyncio和aiohttp開發的一個輕便高效的爬蟲架構,采用了scrapy的設計模式,參考了github上一些開源架構的處理邏輯。
asyncpy的架構及流程
安裝需要的環境
python版本需要 >=3.6
依賴包: [ 'lxml', 'parsel','docopt', 'aiohttp']
安裝指令:
pip install asyncpy
如果安裝報錯:
ERROR: Could not find a version that satisfies the requirement asyncpy (from versions: none)
ERROR: No matching distribution found for asyncpy
請檢視你目前的python版本,python版本需要3.6以上。
還無法下載下傳的話,可以到 https://pypi.org/project/asyncpy/ 下載下傳最新版本的 whl 檔案。
點選Download files,下載下傳完成之後使用cmd安裝:
pip install asyncpy-版本-py3-none-any.whl
建立一個爬蟲檔案
在指令行輸入asyncpy --version 檢視是否成功安裝。
建立demo檔案,使用cmd指令:
asyncpy genspider demo
全局settings
settings配置
簡介
CONCURRENT_REQUESTS
并發數量
RETRIES
重試次數
DOWNLOAD_DELAY
下載下傳延時
RETRY_DELAY
重試延時
DOWNLOAD_TIMEOUT
逾時限制
USER_AGENT
使用者代理
LOG_FILE
日志路徑
LOG_LEVEL
日志等級
USER_AGENT
全局UA
PIPELINES
管道
MIDDLEWARE
中間件
如果要啟動全局settings的話,需要在spider檔案中通過settings_attr 傳入settings:
import settings
class DemoSpider(Spider):
name = 'demo'
start_urls = []
settings_attr = settings
自定義settings
如果需要對單個爬蟲檔案進行settings配置,可以像scrapy一樣在爬蟲檔案中引入 custom_settings。
他與settings_attr 并不沖突。
class DemoSpider2(Spider):
name = 'demo2'
start_urls = []
concurrency = 30 # 并發數量
custom_settings = {
"RETRIES": 1, # 重試次數
"DOWNLOAD_DELAY": 0, # 下載下傳延時
"RETRY_DELAY": 0, # 重試延時
"DOWNLOAD_TIMEOUT": 10, # 逾時時間
"LOG_FILE":"demo2.log" # 日志檔案
}
生成日志檔案
在settings檔案中,加入:
LOG_FILE = './asyncpy.log'
LOG_LEVEL = 'DEBUG'
如果需要對多個爬蟲生成多個日志檔案,
需要删除settings中的日志配置,在custom_settings中重新進行配置。
自定義Middleware中間件
在建立的 demo_middleware 檔案中,增加新的功能。
可以根據 request.meta 和spider 的屬性進行針對性的操作。
from asyncpy.middleware import Middleware
middleware = Middleware()
@middleware.request
async def UserAgentMiddleware(spider, request):
if request.meta.get('valid'):
print("目前爬蟲名稱:%s"%spider.name)
ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36"
request.headers.update({"User-Agent": ua})
@middleware.request
async def ProxyMiddleware(spider, request):
if spider.name == 'demo':
request.aiohttp_kwargs.update({"proxy": "http://123.45.67.89:0000"})
方法1、去settings檔案中開啟管道。(版本更新,暫時請選擇2方法)
MIDDLEWARE = [
'demo_middleware.middleware',
]
方法2、在start()傳入middleware:
from middlewares import middleware
DemoSpider.start(middleware=middleware)
自定義Pipelines管道
如果你定義了item(目前隻支援dict字典格式的item),并且settings 裡面 啟用了pipelines 那麼你就可以在pipelines 裡面 編寫 連接配接資料庫,插入資料的代碼。
在spider檔案中:
item = {}
item['response'] = response.text
item['datetime'] = '2020-05-21 13:14:00'
yield item
在pipelines.py檔案中:
class SpiderPipeline():
def __init__(self):
pass
def process_item(self, item, spider_name):
pass
方法1、settings中開啟管道:(版本更新,暫時請選擇2方法)
PIPELINES = [
'pipelines.SpiderPipeline',
]
方法2、在start()傳入pipelines:
from pipelines import SpiderPipeline
DemoSpider.start(pipelines=SpiderPipeline)
Post請求 重寫start_requests
如果需要直接發起 post請求,可以删除 start_urls 中的元素,重新 start_requests 方法。
解析response
采用了scrapy中的解析庫parse,解析方法和scrapy一樣,支援xpath,css選擇器,re。
簡單示例:
xpath("//div[id = demo]/text()").get() ----- 擷取第一個元素
xpath("//div[id = demo]/text()").getall() ----- 擷取所有元素,傳回list
啟動爬蟲
在spider檔案中通過 類名.start()啟動爬蟲。
比如爬蟲的類名為DemoSpider
DemoSpider.start()
啟動多個爬蟲
這裡并沒有進行完善,可以采用多程序的方式進行測試。
from Demo.demo import DemoSpider
from Demo.demo2 import DemoSpider2
import multiprocessing
def open_DemoSpider2():
DemoSpider2.start()
def open_DemoSpider():
DemoSpider.start()
if __name__ == "__main__":
p1 = multiprocessing.Process(target = open_DemoSpider)
p2 = multiprocessing.Process(target = open_DemoSpider2)
p1.start()
p2.start()
特别緻謝 : Scrapy、Ruia、Looter、asyncio、aiohttp
更多詳細内容可參考demo,連結: Asyncpy使用文檔
感興趣可以去 github 點個star ,感謝大家!