Posted in Python onSeptember 18, 2016
本文实例讲述了Python3实现并发检验代理池地址的方法。分享给大家供大家参考,具体如下:
#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/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)', } #检验单个代理的有效性 #如果有效,返回该proxy;否则,返回空字符串 def Check(desturl, proxy, feature): proxies = {'http': 'http://' + proxy} r = None #声明 exMsg = None try: r = requests.get(url=desturl, headers=Headers, proxies=proxies, timeout=3) except: exMsg = '* ' + traceback.format_exc() #print(exMsg) finally: if 'r' in locals() and r: r.close() if exMsg: return '' if r.status_code != 200: return '' if r.text.find(feature) < 0: return '' return proxy #输入代理列表(set/list),返回有效代理列表 def GetValidProxyPool(rawProxyPool, desturl, feature): validProxyList = list() #有效代理列表 pool = futures.ThreadPoolExecutor(8) futureList = list() for proxy in rawProxyPool: futureList.append(pool.submit(Check, desturl, proxy, feature)) print('\n submit done, waiting for responses\n') for future in futures.as_completed(futureList): proxy = future.result() print('proxy:' + proxy) if proxy: #有效代理 validProxyList.append(proxy) print('validProxyList size:' + str(len(validProxyList))) return validProxyList #获取原始代理池 def GetRawProxyPool(): rawProxyPool = set() #通过某种方式获取原始代理池...... return rawProxyPool if __name__ == "__main__": rawProxyPool = GetRawProxyPool() desturl = 'http://...' #需要通过代理访问的目标地址 feature = 'xxx' #目标网页的特征码 validProxyPool = GetValidProxyPool(rawProxyPool, desturl, feature)
希望本文所述对大家Python程序设计有所帮助。
Python3实现并发检验代理池地址的方法
- Author -
RQSLT声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@