首页 > 技术文章 > 验证代理IP

one-lightyear 2017-04-12 23:31 原文

#
#author:wuhao
#
import
urllib.requestfrom http import cookiejar import xlrd import threading #有效的代理,可添加一个全局变量用于存储,然后保存到文件
#这里由于可行的代理IP太少,就未保存至本地
def Validate_proxy(url,proxy): opener.add_handler(urllib.request.ProxyHandler(proxy),lock) try: opener.open(url,timeout=3)
     lock.acquire()
for key,value in proxy.items(): print(value+" has successed")
     lock.release()
except:
     lock.acquire()
for key,value in proxy.items(): print(value+" has failed")
     lock.release() #获取代理转换为{“http":"http://ip:port"}格式
def getProxy(ip,port): global index proxy={"http":"http://"+ip[index]+":"+port[index]} index += 1 return proxy
#从excel中读取数据
def GetData(): #打开xls data=xlrd.open_workbook("proxy.xls") #获取工作表 table=data.sheets()[0] #用于存储代理IP 和 端口 proxy_ip=[] proxy_port=[] #获取行数 row=table.nrows #循环写入IP和端口 for line in range(1,row): if table.row_values(line)[0]!="" and table.row_values(line)[1]!="": proxy_ip.append(table.row_values(line)[0]) proxy_port.append(table.row_values(line)[1]) return proxy_ip,proxy_port if __name__=="__main__": proxy_ip=GetData()[0] proxy_port=GetData()[1] # 全局变量 index = 0

  #用于测试的网站,可以查看IP url="http://1212.ip138.com/ic.asp" cookie=cookiejar.CookieJar() opener=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie))    lock=threading.Lock() while index!=proxy_ip.__len__():
       t1
=threading.Thread(target=Validate_proxy,args=(url,getProxy(proxy_ip,proxy_port),lock))      t1.start()

                                                                          #欢迎大家评论指导

 

推荐阅读