Python 代理验证程序(For 无忧代理) 多线程版

转发-来自http://www.redicecn.com/html/Python/20101209/204.html

与之前的版本http://www.redicecn.com/html/yuanchuangchengxu/20101205/201.html相 比,这个使用了多线程。验证时间由原来的20分钟缩短到现在的1分钟左右。

 直接上源码:

与之前的版本http://www.redicecn.com/html/yuanchuangchengxu/20101205/201.html相 比,这个使用了多线程。验证时间由原来的20分钟缩短到现在的1分钟左右。

   

直接上源码:

  1. # coding:gbk  
  2. # 验证最新可用代 理 For http://www.5uproxy.net 多线程版  
  3. # by redice 2010.12.09  
  4.   
  5. import sys  
  6. reload(sys)  
  7. sys.setdefaultencoding('gbk')  
  8.   
  9.   
  10. import urllib  
  11. import urllib2  
  12. from urllib2 import URLError, HTTPError  
  13.   
  14. DEBUG = True  
  15.   
  16. #html页面下载函数  
  17. def getHtml(url,post_data=None,cookie=None):  
  18.         """Fetch the target html 
  19.         url - URL to fetch 
  20.         post_data - POST Entity 
  21.         cookie - Cookie Header 
  22.         """  
  23.         if DEBUG:  
  24.             print "getHtml: ",url  
  25.   
  26.         result =''  
  27.           
  28.         try:  
  29.             #create a request  
  30.             request = urllib2.Request(url)  
  31.   
  32.             #change User-Agent  
  33.             request.add_header('User-Agent','Mozilla/5.0')  
  34.               
  35.             #change Referrer  
  36.             request.add_header('Referrer',url)  
  37.               
  38.             #if has cookie,add cookie header  
  39.             if cookie:  
  40.                request.add_header('Cookie',cookie)  
  41.   
  42.             #create a opener  
  43.             opener = urllib2.build_opener()              
  44.              
  45.             #if has post entity  
  46.             if post_data:  
  47.                 #encode post data  
  48.                 post_data = urllib.urlencode(post_data)  
  49.                   
  50.                 response = opener.open(request,post_data)  
  51.             else:  
  52.                 response = opener.open(request)  
  53.               
  54.             result = response.read()  
  55.                   
  56.             response.close()  
  57.   
  58.             #no content,don't save  
  59.             if not result or len(result)==0:  
  60.                 return ''  
  61.               
  62.             return  result  
  63.         except HTTPError, e:  
  64.             if DEBUG:  
  65.                 print 'Error retrieving data:',e  
  66.                 print 'Server error document follows:\n'  
  67.                 #print e.read()  
  68.             return ''  
  69.         except URLError, e:  
  70.             if hasattr(e, 'reason'):  
  71.                 if DEBUG:  
  72.                     print 'Failed to reach a server.'  
  73.                     print 'Reason: ', e.reason  
  74.                 return ''  
  75.             elif hasattr(e, 'code'):  
  76.                 if DEBUG:  
  77.                     print 'The server couldn\'t fulfill the request.'  
  78.                     print 'Error code: ', e.code  
  79.                 return ''  
  80.         except Exception, e:  
  81.             if DEBUG:  
  82.                 print e  
  83.             return ''  
  84.           
  85.   
  86. #需要验证的代理列表  
  87. proxy_urls = []  
  88. proxy_urls.append({'url':'http://www.5uproxy.net/http_fast.html','type':'http_fast'})  
  89. proxy_urls.append({'url':'http://www.5uproxy.net/http_anonymous.html','type':'http_anonymous'})  
  90. proxy_urls.append({'url':'http://www.5uproxy.net/http_non_anonymous.html','type':'http_transparent'})  
  91. proxy_urls.append({'url':'http://www.5uproxy.net/socks5.html','type':'socks5'})  
  92.   
  93.   
  94. import re  
  95. import socket  
  96. import time  
  97. import threading  
  98.   
  99. result =[]  
  100.   
  101.   
  102. #线程同步锁  
  103. lock = threading.Lock()   
  104.   
  105. def synchronous(f):  
  106.     def call(*args, **kwargs):  
  107.         lock.acquire()  
  108.         try:  
  109.             return f(*args, **kwargs)  
  110.         finally:  
  111.             lock.release()  
  112.     return call  
  113.   
  114.   
  115.   
  116. # 先获取所有待验证的代理  
  117. proxies = []  
  118.   
  119. for proxy_url in proxy_urls:  
  120.     html = getHtml(proxy_url['url'])  
  121.       
  122.     #正则匹配获取每一代理  
  123.     rs = re.compile(r'''''<tr .*?>[\s\S]*?<td .*?>\d+?</td>[\s\S]*?<td>(\S+?)</td>[\s\S]*?<td .*?>(\S+?)</td>[\s\S]*?<td .*?>(\S+?)</td>[\s\S]*?</tr>''',re.DOTALL).findall(html)  
  124.       
  125.     for r in rs:  
  126.         proxy = {}  
  127.           
  128.         #代理域名  
  129.         proxy['domain'] = r[0]  
  130.         #代理端口  
  131.         proxy['port'] = r[1]  
  132.         #代理国家  
  133.         proxy['state'] = r[2]  
  134.         #代理类型  
  135.         proxy['type'] = proxy_url['type']  
  136.         #响应时间  
  137.         proxy['time'] = 0  
  138.           
  139.         if not (proxy in proxies):  
  140.             proxies.append(proxy)  
  141.   
  142.   
  143.   
  144. # 获取一个待验证代理  
  145. @synchronous  
  146. def getproxy():  
  147.     global proxies  
  148.     if len(proxies)>0:  
  149.         return proxies.pop()  
  150.     else:  
  151.         return ''  
  152.   
  153.   
  154.       
  155. #保存验证结果  
  156. @synchronous  
  157. def saveresult(proxy):  
  158.     global result  
  159.       
  160.     if not(proxy in result):  
  161.         result.append(proxy)  
  162.   
  163.   
  164. #线程函数  
  165. def verify():  
  166.       
  167.     while 1:  
  168.         proxy = getproxy()  
  169.         #所有代理均已验证完毕  
  170.         if len(proxy)==0:  
  171.             return  
  172.           
  173.         print "正在验证:%s,%s" % (proxy['domain'],proxy['port'])  
  174.           
  175.         #验证代理的可用性  
  176.         #创建一个TCP连接套接字  
  177.         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  178.         #设置10超时  
  179.         sock.settimeout(10)  
  180.         try:  
  181.             start = time.clock()  
  182.               
  183.             #连接代理服务器  
  184.             sock.connect((proxy['domain'], int(proxy['port'])))  
  185.             proxy['time'] = int((time.clock() - start) * 1000)   
  186.             sock.close()  
  187.               
  188.             saveresult(proxy)  
  189.             print "%s,%s 验证通过,响应时间:%d ms." % (proxy['domain'],proxy['port'],proxy['time'])  
  190.         except Exception, e:  
  191.             if DEBUG:  
  192.                 print e  
  193.               
  194.             print "%s,%s 验 证失败." % (proxy['domain'],proxy['port'])  
  195.   
  196.   
  197.   
  198.   
  199. #init thread_pool   
  200. thread_pool = []  
  201.   
  202. for i in range(20):   
  203.     th = threading.Thread(target=verify,args=()) ;   
  204.     thread_pool.append(th)  
  205.   
  206. # start threads one by one           
  207. for thread in thread_pool:   
  208.     thread.start()  
  209.   
  210. #collect all threads   
  211. for thread in thread_pool:   
  212.     threading.Thread.join(thread)  
  213.   
  214.   
  215. #结果按响应时间从小到大排序  
  216.   
  217. result.sort(lambda x,y: cmp(x['time'], y['time']))    
  218.   
  219. fname = 'proxy_'+ time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time())) +'.txt'  
  220. file = open(fname,'w')  
  221.   
  222. print "验证结果如下:"  
  223. for item in result:  
  224.      str = '%s:%s   %s,%s,%d' % (item['domain'],item['port'],item['type'],item['state'],item['time'])  
  225.     print str  
  226.     file.write(str+'\n')  
  227.       
  228. file.close()  
  229.   
  230. print "所有代理已验证完 毕,共计%d个验证通过。验证通过的代理已存入%s" % (len(result),fname)  
  231.       
原文地址:https://www.cnblogs.com/baizx/p/1939619.html