Python,检查代理是否还活着? [英] Python, checking if a proxy is alive?

查看:63
本文介绍了Python,检查代理是否还活着?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

 for item in pxfile.readlines():
     if is_OK(item):
         sys.stdout.write(item + "is not OK.")
         item = make(item)
         item = "#" + item
         resfile.write(item)
     else:
         sys.stdout.write(item)
         sys.stdout.write("is OK.")
         line = make(item)
         resfile.write(item)

如果 is_OK 为真,则表示代理不存在,应修复该问题.

If is_OK is true it means that the proxy doesn't exist, should fix that.

def is_OK(ip):
    try:
        proxy_handler = urllib2.ProxyHandler({'http': ip})
        opener = urllib2.build_opener(proxy_handler)
        opener.addheaders = [('User-agent', 'Mozilla/5.0')]
        urllib2.install_opener(opener)
        req=urllib2.Request('http://www.icanhazip.com')
        sock=urllib2.urlopen(req)
    except urllib2.HTTPError, e:
        #print 'Error code: ', e.code
        return e.code
    except Exception, detail:

        #print "ERROR:", detail
        return 1
    return 0

得到这样的列表需要 10 分钟:

It takes 10 minutes to get a list like this:

141.219.252.132:68664
is OK.118.174.0.155:8080
is OK.91.194.246.169:8080
is not OK.91.194.246.81:8080
is OK.201.245.110.138:8888
is OK.202.43.178.31:3128
is OK.202.109.80.106:8080

  1. 有没有办法让它更快?
  2. 格式不正确,我尝试使用 strip() 删除换行符但没有运气.

有什么想法吗?

推荐答案

你应该使用线程来让代码运行得更快:

You should use threads to make the code run quicker :

import urllib2, threading

def is_OK(ip):
    print 'Trying %s ...' % ip
    try:
        proxy_handler = urllib2.ProxyHandler({'http': ip})
        opener = urllib2.build_opener(proxy_handler)
        opener.addheaders = [('User-agent', 'Mozilla/5.0')]
        urllib2.install_opener(opener)
        req=urllib2.Request('http://www.icanhazip.com')
        urllib2.urlopen(req)
        print '%s is OK' % ip
    except urllib2.HTTPError:
        print '%s is not OK' % ip
    except Exception:
        print '%s is not OK' % ip

a = threading.Thread(None, is_OK, None, ("hostname1",), None)
a.start()
b = threading.Thread(None, is_OK, None, ("hostname2",), None)
b.start()

这篇关于Python,检查代理是否还活着?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆