使用 Scrapy + MongoDB, 下載 + 保存 + 校驗 + 更新代理

1.先提供源碼

源碼地址

2.原因,想法:

  1. 其實 github 也有很多類似的工具, 總是覺得沒有自己寫的用著順手。
  2. 比如,我需要把代理分中外2種,那么遲早要自己來動手做的。

3.下載

  1. 這里我找到了4個提供免費代理的網(wǎng)站,其中3個是用 scrapy 寫的,另外一個是用 requests 寫的。以后還可以添加新的。
  2. 全都保存在同一個數(shù)據(jù)集里面,即 MongDBcollections, 以下的數(shù)據(jù)集指的都是這個。

4.校驗

  1. 標(biāo)準(zhǔn) :響應(yīng)時間 timeout=1 , 而且 返回結(jié)果,與自己真實的 ip 不相等時,那么就是好用的。
def check_status(self, p):
    url = "http://httpbin.org/ip"
    resp = requests.get(url, proxies=p, timeout=1)
    if resp.status_code == 200 and resp.json()["origin"] != self.real_ip:
        print("This is a good one!", p)
  1. 用哪種多線程:
    2.1 aiohttp + asyncio 這個組合我試了,不合適。
    2.2 multiprocessing.dummy.Pool ,如果遇到一個線程出問題,整體就退出了,不行。
    2.3 最終我還是選擇 下面這種寫法:
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED

def run(self):
    raw_data = self.db[self.coll_name].find()
    with ThreadPoolExecutor(max_workers=50) as executor:
        future_tasks = [executor.submit(self.check_status, p) for p in raw_data]
        wait(future_tasks, return_when=ALL_COMPLETED)

5.保存 (講真的, 這里才是我想說的重點)

  1. 數(shù)據(jù)集的名稱問題: 如果每次都新建一個數(shù)據(jù)集,那么每次都要起名字,而且在別處調(diào)用的話,更是不方便。
  2. 直接修原始數(shù)據(jù):使用多線程進行校驗的過程中,把劣質(zhì)的代理刪掉,這一步執(zhí)行是失敗的。
  3. 綜上,我是把有效的代理保存在內(nèi)存中 ,然后再刪掉舊的數(shù)據(jù)集,并使用舊數(shù)據(jù)集的名稱新建一個數(shù)據(jù)集。
# self.good = []
self.db.drop_collection(self.coll_name)
self.db[self.coll_name].insert_many(self.good)
  1. 代理分中外,思路也是一樣的。

6.使用

  1. 在自己需要的時候,可以寫入:
from pymongo import MongoClient

# 也可以更簡潔,寫成列表推導(dǎo)式
data = MongoClient('localhost', 27017)['proxies_db']['proxies_coll'].find()
for dic in data:
    print({f'{dic["protocol"].lower()}': f'{dic["protocol"].lower()}://{dic["ip"]}:{dic["port"]}'})
  1. 或是在 scrapy 中寫一個代理中間件

DOWNLOADER_MIDDLEWARES = {'core_2048.middlewares.ProxyMiddleware': 543,} # stttings.py

from pymongo import MongoClient

class ProxyMiddleware(object):
    def __init__(self):
        self.data = MongoClient('localhost', 27017)['proxies_db']['world'].find()
        self.proxies = [f'{dic["protocol"].lower()}://{dic["ip"]}:{dic["port"]}' for dic in self.data]

    def process_request(self, request, spider):
        proxy = random.choice(self.proxies)
        request.meta['proxy'] = proxy
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容