1.先提供源碼
2.原因,想法:
- 其實 github 也有很多類似的工具, 總是覺得沒有自己寫的用著順手。
- 比如,我需要把代理分中外2種,那么遲早要自己來動手做的。
3.下載
- 這里我找到了4個提供免費代理的網(wǎng)站,其中3個是用 scrapy 寫的,另外一個是用 requests 寫的。以后還可以添加新的。
- 全都保存在同一個數(shù)據(jù)集里面,即 MongDB 的 collections, 以下的數(shù)據(jù)集指的都是這個。
4.校驗
- 標(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)
- 用哪種多線程:
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.保存 (講真的, 這里才是我想說的重點)
- 數(shù)據(jù)集的名稱問題: 如果每次都新建一個數(shù)據(jù)集,那么每次都要起名字,而且在別處調(diào)用的話,更是不方便。
- 直接修原始數(shù)據(jù):使用多線程進行校驗的過程中,把劣質(zhì)的代理刪掉,這一步執(zhí)行是失敗的。
- 綜上,我是把有效的代理保存在內(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)
- 代理分中外,思路也是一樣的。
6.使用
- 在自己需要的時候,可以寫入:
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"]}'})
- 或是在 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