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 为真,说明代理不存在,这个问题需要解决。
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分钟:
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
- 有没有办法让这个过程更快一些?
- 格式很糟糕,我试着用 strip() 去掉换行符,但没成功。
有什么想法吗?
3 个回答
1
关于格式化,像这样使用strip()应该是没问题的:
for line in pxfile:
item = line.strip()
if is_OK(item):
sys.stdout.write(item + " is not OK.\n")
resfile.write("# " + make(item) +"\n")
else:
sys.stdout.write(item + " is OK.\n")
resfile.write(make(item) +"\n")
1
第一个想法是,把默认的超时时间设置得短一些。
timeout = 10
sock=urllib2.urlopen(req, None, timeout)
你还可以使用多线程,这样就可以同时测试多个连接。
2
你应该使用线程来让代码运行得更快:
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()