首页 >后端开发 >Python教程 >Python3实现并发检验代理池地址的方法

Python3实现并发检验代理池地址的方法

高洛峰
高洛峰原创
2017-02-22 16:38:201516浏览

本文实例讲述了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 &#39;&#39;
  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(&#39;\n submit done, waiting for responses\n&#39;)
  for future in futures.as_completed(futureList):
    proxy = future.result()
    print(&#39;proxy:&#39; + proxy)
    if proxy: #有效代理
      validProxyList.append(proxy)
  print(&#39;validProxyList size:&#39; + str(len(validProxyList)))
  return validProxyList
#获取原始代理池
def GetRawProxyPool():
  rawProxyPool = set()
  #通过某种方式获取原始代理池......
  return rawProxyPool
if __name__ == "__main__":
  rawProxyPool = GetRawProxyPool()
  desturl = &#39;http://...&#39;    #需要通过代理访问的目标地址
  feature = &#39;xxx&#39;    #目标网页的特征码
  validProxyPool = GetValidProxyPool(rawProxyPool, desturl, feature)


更多Python3实现并发检验代理池地址的方法相关文章请关注PHP中文网!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn