Python實(shí)現(xiàn)的異步代理爬蟲及代理池
使用python asyncio實(shí)現(xiàn)了一個異步代理池,根據(jù)規(guī)則爬取代理網(wǎng)站上的免費(fèi)代理,在驗(yàn)證其有效后存入redis中,定期擴(kuò)展代理的數(shù)量并檢驗(yàn)池中代理的有效性,移除失效的代理。同時(shí)用aiohttp實(shí)現(xiàn)了一個server,其他的程序可以通過訪問相應(yīng)的url來從代理池中獲取代理。
源碼
環(huán)境
- Python 3.5+
- Redis
- PhantomJS(可選)
- Supervisord(可選)
因?yàn)榇a中大量使用了asyncio的async和await語法,它們是在Python3.5中才提供的,所以最好使用Python3.5及以上的版本,我使用的是Python3.6。
依賴
- redis
- aiohttp
- bs4
- lxml
- requests
- selenium
selenium包主要是用來操作PhantomJS的。
下面來對代碼進(jìn)行說明。
1. 爬蟲部分
核心代碼
async def start(self):
for rule in self._rules:
parser = asyncio.ensure_future(self._parse_page(rule)) # 根據(jù)規(guī)則解析頁面來獲取代理
logger.debug('{0} crawler started'.format(rule.__rule_name__))
if not rule.use_phantomjs:
await page_download(ProxyCrawler._url_generator(rule), self._pages, self._stop_flag) # 爬取代理網(wǎng)站的頁面
else:
await page_download_phantomjs(ProxyCrawler._url_generator(rule), self._pages,
rule.phantomjs_load_flag, self._stop_flag) # 使用PhantomJS爬取
await self._pages.join()
parser.cancel()
logger.debug('{0} crawler finished'.format(rule.__rule_name__))
上面的核心代碼實(shí)際上是一個用asyncio.Queue實(shí)現(xiàn)的生產(chǎn)-消費(fèi)者模型,下面是該模型的一個簡單實(shí)現(xiàn):
import asyncio
from random import random
async def produce(queue, n):
for x in range(1, n + 1):
print('produce ', x)
await asyncio.sleep(random())
await queue.put(x) # 向queue中放入item
async def consume(queue):
while 1:
item = await queue.get() # 等待從queue中獲取item
print('consume ', item)
await asyncio.sleep(random())
queue.task_done() # 通知queue當(dāng)前item處理完畢
async def run(n):
queue = asyncio.Queue()
consumer = asyncio.ensure_future(consume(queue))
await produce(queue, n) # 等待生產(chǎn)者結(jié)束
await queue.join() # 阻塞直到queue不為空
consumer.cancel() # 取消消費(fèi)者任務(wù),否則它會一直阻塞在get方法處
def aio_queue_run(n):
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(run(n)) # 持續(xù)運(yùn)行event loop直到任務(wù)run(n)結(jié)束
finally:
loop.close()
if __name__ == '__main__':
aio_queue_run(5)
運(yùn)行上面的代碼,一種可能的輸出如下:
produce 1 produce 2 consume 1 produce 3 produce 4 consume 2 produce 5 consume 3 consume 4 consume 5
爬取頁面
async def page_download(urls, pages, flag):
url_generator = urls
async with aiohttp.ClientSession() as session:
for url in url_generator:
if flag.is_set():
break
await asyncio.sleep(uniform(delay - 0.5, delay + 1))
logger.debug('crawling proxy web page {0}'.format(url))
try:
async with session.get(url, headers=headers, timeout=10) as response:
page = await response.text()
parsed = html.fromstring(decode_html(page)) # 使用bs4來輔助lxml解碼網(wǎng)頁:http://lxml.de/elementsoup.html#Using only the encoding detection
await pages.put(parsed)
url_generator.send(parsed) # 根據(jù)當(dāng)前頁面來獲取下一頁的地址
except StopIteration:
break
except asyncio.TimeoutError:
logger.error('crawling {0} timeout'.format(url))
continue # TODO: use a proxy
except Exception as e:
logger.error(e)
使用aiohttp實(shí)現(xiàn)的網(wǎng)頁爬取函數(shù),大部分代理網(wǎng)站都可以使用上面的方法來爬取,對于使用js動態(tài)生成頁面的網(wǎng)站可以使用selenium控制PhantomJS來爬取——本項(xiàng)目對爬蟲的效率要求不高,代理網(wǎng)站的更新頻率是有限的,不需要頻繁的爬取,完全可以使用PhantomJS。
解析代理
最簡單的莫過于用xpath來解析代理了,使用Chrome瀏覽器的話,直接通過右鍵就能獲得選中的頁面元素的xpath:

安裝Chrome的擴(kuò)展“XPath Helper”就可以直接在頁面上運(yùn)行和調(diào)試xpath,十分方便:

BeautifulSoup不支持xpath,使用lxml來解析頁面,代碼如下:
async def _parse_proxy(self, rule, page):
ips = page.xpath(rule.ip_xpath) # 根據(jù)xpath解析得到list類型的ip地址集合
ports = page.xpath(rule.port_xpath) # 根據(jù)xpath解析得到list類型的ip地址集合
if not ips or not ports:
logger.warning('{2} crawler could not get ip(len={0}) or port(len={1}), please check the xpaths or network'.
format(len(ips), len(ports), rule.__rule_name__))
return
proxies = map(lambda x, y: '{0}:{1}'.format(x.text.strip(), y.text.strip()), ips, ports)
if rule.filters: # 根據(jù)過濾字段來過濾代理,如“高匿”、“透明”等
filters = []
for i, ft in enumerate(rule.filters_xpath):
field = page.xpath(ft)
if not field:
logger.warning('{1} crawler could not get {0} field, please check the filter xpath'.
format(rule.filters[i], rule.__rule_name__))
continue
filters.append(map(lambda x: x.text.strip(), field))
filters = zip(*filters)
selector = map(lambda x: x == rule.filters, filters)
proxies = compress(proxies, selector)
for proxy in proxies:
await self._proxies.put(proxy) # 解析后的代理放入asyncio.Queue中
爬蟲規(guī)則
網(wǎng)站爬取、代理解析、濾等等操作的規(guī)則都是由各個代理網(wǎng)站的規(guī)則類定義的,使用元類和基類來管理規(guī)則類。基類定義如下:
class CrawlerRuleBase(object, metaclass=CrawlerRuleMeta): start_url = None page_count = 0 urls_format = None next_page_xpath = None next_page_host = '' use_phantomjs = False phantomjs_load_flag = None filters = () ip_xpath = None port_xpath = None filters_xpath = ()
各個參數(shù)的含義如下:
start_url(必需)
爬蟲的起始頁面。
ip_xpath(必需)
爬取IP的xpath規(guī)則。
port_xpath(必需)
爬取端口號的xpath規(guī)則。
page_count
爬取的頁面數(shù)量。
urls_format
頁面地址的格式字符串,通過urls_format.format(start_url, n)來生成第n頁的地址,這是比較常見的頁面地址格式。
next_page_xpath,next_page_host
由xpath規(guī)則來獲取下一頁的url(常見的是相對路徑),結(jié)合host得到下一頁的地址:next_page_host + url。
use_phantomjs, phantomjs_load_flag
use_phantomjs用于標(biāo)識爬取該網(wǎng)站是否需要使用PhantomJS,若使用,需定義phantomjs_load_flag(網(wǎng)頁上的某個元素,str類型)作為PhantomJS頁面加載完畢的標(biāo)志。
filters
過濾字段集合,可迭代類型。用于過濾代理。
爬取各個過濾字段的xpath規(guī)則,與過濾字段按順序一一對應(yīng)。
元類CrawlerRuleMeta用于管理規(guī)則類的定義,如:如果定義use_phantomjs=True,則必須定義phantomjs_load_flag,否則會拋出異常,不在此贅述。
目前已經(jīng)實(shí)現(xiàn)的規(guī)則有西刺代理、快代理、360代理、66代理和 秘密代理。新增規(guī)則類也很簡單,通過繼承CrawlerRuleBase來定義新的規(guī)則類YourRuleClass,放在proxypool/rules目錄下,并在該目錄下的__init__.py中添加from . import YourRuleClass(這樣通過CrawlerRuleBase.__subclasses__()就可以獲取全部的規(guī)則類了),重啟正在運(yùn)行的proxy pool即可應(yīng)用新的規(guī)則。
2. 檢驗(yàn)部分
免費(fèi)的代理雖然多,但是可用的卻不多,所以爬取到代理后需要對其進(jìn)行檢驗(yàn),有效的代理才能放入代理池中,而代理也是有時(shí)效性的,還要定期對池中的代理進(jìn)行檢驗(yàn),及時(shí)移除失效的代理。
這部分就很簡單了,使用aiohttp通過代理來訪問某個網(wǎng)站,若超時(shí),則說明代理無效。
async def validate(self, proxies):
logger.debug('validator started')
while 1:
proxy = await proxies.get()
async with aiohttp.ClientSession() as session:
try:
real_proxy = 'http://' + proxy
async with session.get(self.validate_url, proxy=real_proxy, timeout=validate_timeout) as resp:
self._conn.put(proxy)
except Exception as e:
logger.error(e)
proxies.task_done()
3. server部分
使用aiohttp實(shí)現(xiàn)了一個web server,啟動后,訪問http://host:port即可顯示主頁:

- 訪問http://host:port/get來從代理池獲取1個代理,如:'127.0.0.1:1080';
- 訪問http://host:port/get/n來從代理池獲取n個代理,如:"['127.0.0.1:1080', '127.0.0.1:443', '127.0.0.1:80']";
- 訪問http://host:port/count來獲取代理池的容量,如:'42'。
因?yàn)橹黜撌且粋€靜態(tài)的html頁面,為避免每來一個訪問主頁的請求都要打開、讀取以及關(guān)閉該html文件的開銷,將其緩存到了redis中,通過html文件的修改時(shí)間來判斷其是否被修改過,如果修改時(shí)間與redis緩存的修改時(shí)間不同,則認(rèn)為html文件被修改了,則重新讀取文件,并更新緩存,否則從redis中獲取主頁的內(nèi)容。
返回代理是通過aiohttp.web.Response(text=ip.decode('utf-8'))實(shí)現(xiàn)的,text要求str類型,而從redis中獲取到的是bytes類型,需要進(jìn)行轉(zhuǎn)換。返回的多個代理,使用eval即可轉(zhuǎn)換為list類型。
返回主頁則不同,是通過aiohttp.web.Response(body=main_page_cache, content_type='text/html') ,這里body要求的是bytes類型,直接將從redis獲取的緩存返回即可,conten_type='text/html'必不可少,否則無法通過瀏覽器加載主頁,而是會將主頁下載下來——在運(yùn)行官方文檔中的示例代碼的時(shí)候也要注意這點(diǎn),那些示例代碼基本上都沒有設(shè)置content_type。
這部分不復(fù)雜,注意上面提到的幾點(diǎn),而關(guān)于主頁使用的靜態(tài)資源文件的路徑,可以參考之前的博客《aiohttp之添加靜態(tài)資源路徑》。
4. 運(yùn)行
將整個代理池的功能分成了3個獨(dú)立的部分:
proxypool
定期檢查代理池容量,若低于下限則啟動代理爬蟲并對代理檢驗(yàn),通過檢驗(yàn)的爬蟲放入代理池,達(dá)到規(guī)定的數(shù)量則停止爬蟲。
proxyvalidator
用于定期檢驗(yàn)代理池中的代理,移除失效代理。
proxyserver
啟動server。
這3個獨(dú)立的任務(wù)通過3個進(jìn)程來運(yùn)行,在Linux下可以使用supervisod來=管理這些進(jìn)程,下面是supervisord的配置文件示例:
; supervisord.conf [unix_http_server] file=/tmp/supervisor.sock [inet_http_server] port=127.0.0.1:9001 [supervisord] logfile=/tmp/supervisord.log logfile_maxbytes=5MB logfile_backups=10 loglevel=debug pidfile=/tmp/supervisord.pid nodaemon=false minfds=1024 minprocs=200 [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///tmp/supervisor.sock [program:proxyPool] command=python /path/to/ProxyPool/run_proxypool.py redirect_stderr=true stdout_logfile=NONE [program:proxyValidator] command=python /path/to/ProxyPool/run_proxyvalidator.py redirect_stderr=true stdout_logfile=NONE [program:proxyServer] command=python /path/to/ProxyPool/run_proxyserver.py autostart=false redirect_stderr=true stdout_logfile=NONE
因?yàn)轫?xiàng)目自身已經(jīng)配置了日志,所以這里就不需要再用supervisord捕獲stdout和stderr了。通過supervisord -c supervisord.conf啟動supervisord,proxyPool和proxyServer則會隨之自動啟動,proxyServer需要手動啟動,訪問http://127.0.0.1:9001即可通過網(wǎng)頁來管理這3個進(jìn)程了:

supervisod的官方文檔說目前(版本3.3.1)不支持python3,但是我在使用過程中沒有發(fā)現(xiàn)什么問題,可能也是由于我并沒有使用supervisord的復(fù)雜功能,只是把它當(dāng)作了一個簡單的進(jìn)程狀態(tài)監(jiān)控和啟停工具了。
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持腳本之家!
相關(guān)文章
Python如何通過百度翻譯API實(shí)現(xiàn)翻譯功能
這篇文章主要介紹了Python如何通過百度翻譯API實(shí)現(xiàn)翻譯功能,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
Django開發(fā)web后端對比SpringBoot示例分析
這篇文章主要介紹了Django開發(fā)web后端對比SpringBoot示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
Flask框架運(yùn)用Axios庫實(shí)現(xiàn)前后端交互詳解
Axios 是一個基于promise的HTTP庫,該庫是一個更好的替代ajax向后端發(fā)送數(shù)據(jù)或請求數(shù)據(jù)的前端組件庫。本文通過示例為大家介紹了如何運(yùn)用Axios庫實(shí)現(xiàn)前后端交互,感興趣的可以了解一下2022-12-12
Python開發(fā)畢設(shè)案例之桌面學(xué)生信息管理程序
畢業(yè)設(shè)計(jì)必備案例:Python開發(fā)桌面程序2021-11-11
Python使用海龜繪圖實(shí)現(xiàn)貪吃蛇游戲
這篇文章主要為大家詳細(xì)介紹了Python使用海龜繪圖實(shí)現(xiàn)貪吃蛇游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-06-06
Pycharm-community-2020.2.3 社區(qū)版安裝教程圖文詳解
這篇文章主要介紹了Pycharm-community-2020.2.3 社區(qū)版安裝教程圖文詳解,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
django序列化時(shí)使用外鍵的真實(shí)值操作
這篇文章主要介紹了django序列化時(shí)使用外鍵的真實(shí)值操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07

