Python 官方文档:入门教程 => 点击学习
【用线程池并发检验代理有效性】#encoding=utf-8 #author: walker #date: 2016-04-14 #summary: 用线程池并发检验代理有效性 import os, sys, time import re
#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 ***
--结束END--
本文标题: Python3并发检验代理池地址
本文链接: https://lsjlt.com/news/192587.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0