Python3并发检验代理池地址
短信预约 -IT技能 免费直播动态提醒
【用线程池并发检验代理有效性】
#encoding=utf-8
#author: walker
#date: 2016-04-14
#summary: 用线程池并发检验代理有效性
import os, sys, time
import requests
from concurrent import futures
cur_dir_fullpath = os.path.dirname(os.path.abspath(__file__))
Headers = {
'Accept': '**',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko',
}
#检验单个代理的有效性
#如果有效,返回该proxy;否则,返回空字符串
async def Check(desturl, proxy, feature):
proxy = 'http://' + proxy
#print('proxy:' + proxy)
exMsg = None
try:
async with aiohttp.ClientSession() as session:
async with session.get(desturl, headers=Headers, proxy=proxy, timeout=10) as resp:
#print(resp.status)
assert resp.status == 200
#print(await resp.text())
html = await resp.text(encoding='utf-8')
except:
exMsg = '* ' + traceback.format_exc()
#print(exMsg)
if exMsg:
return ''
if html.find(feature) < 0:
return ''
return proxy
#输入代理列表(set/list),返回有效代理列表
async def GetValidProxyPool(rawProxyPool, desturl, feature):
print('GetValidProxyPool ...')
validProxyList = list() #有效代理列表
coroList = list()
for proxy in rawProxyPool:
coroList.append(asyncio.ensure_future((Check(desturl, proxy, feature))))
totalSleepTime = 0
for f in asyncio.as_completed(coroList):
proxy = await f
#print('rtn proxy:' + proxy)
if proxy:
validProxyList.append(proxy)
print('validProxyList size: %d' % len(validProxyList))
return validProxyList
#获取原始代理池
def GetRawProxyPool():
rawProxyPool = set()
#通过某种方式获取原始代理池......
return rawProxyPool
if __name__ == "__main__":
startTime = time.time()
rawProxyPool = GetRawProxyPool()
desturl = 'http://...' #需要通过代理访问的目标地址
feature = 'xxx' #目标网页的特征码
print('rawProxyPool size:%d' % len(rawProxyPool))
loop = asyncio.get_event_loop()
validProxyList = loop.run_until_complete(GetValidProxyPool(rawProxyPool, desturl, feature))
loop.close()
print('rawProxyPool size:%d' % len(validProxyList))
print('time cost:%.2fs' % (time.time()-startTime))
【相关阅读】
concurrent.futures.ThreadPoolExecutor (Python documentation,官方)
12.7 创建一个线程池 (python3-cookbook)
What is the best way to send multiple HTTP requests in Python 3? (stackoverflow)
requests 中文文档
aiohttp 文档
*** walker ***
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341