How to implement concurrent verification of proxy pool addresses in Python3

高洛峰
Release: 2017-02-22 16:38:20
Original
1471 people have browsed it

The example in this article describes how Python3 implements concurrent verification of proxy pool addresses. Share it with everyone for your reference, the details are as follows:

#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)
Copy after login


Please pay attention to more related articles on how to implement concurrent verification of proxy pool addresses in Python3 PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template