Python3.4實現(xiàn)從HTTP代理網(wǎng)站批量獲取代理并篩選的方法示例
本文實例講述了Python3.4實現(xiàn)從HTTP代理網(wǎng)站批量獲取代理并篩選的方法。分享給大家供大家參考,具體如下:
最近在寫爬蟲,苦于不采用代理的情況下,默認(rèn)的IP不出幾分鐘就被封了,故而只能尋找代理。原以為找到HTTP代理就萬事大吉了,沒想到從那個網(wǎng)站獲取的代理大部分都是不能用的,只有少部分能用。。。故而無奈之下,只能從那些代理網(wǎng)站大量獲取代理IP,然后再拿過來進(jìn)行進(jìn)一步的篩選,將有效的代理IP提取出來,留待進(jìn)一步使用。
篩選的主要原理是,通過main函數(shù)提取到未經(jīng)篩選的代理rawProxyList,然后通過這些代理嘗試連接目標(biāo)網(wǎng)站(此文中是連接手機新浪網(wǎng))。如果在規(guī)定時間內(nèi)連接成功,則認(rèn)定為有效代理,放到checkedProxyList之中。
__author__ = 'multiangle'
__edition__='python3.4'
import threading
import urllib.request as request
import time
rawProxyList=[]
checkedProxyList=[]
class proxycheck(threading.Thread):
def __init__(self,proxy_list):
threading.Thread.__init__(self)
self.proxy_list=proxy_list
self.timeout=3
self.testurl='http://www.sina.cn/'
self.testStr='手機新浪網(wǎng)'
def checkproxy(self):
cookies=request.HTTPCookieProcessor()
for proxy in self.proxy_list:
handler=request.ProxyHandler({'http':'http://%s'%(proxy)})
opener=request.build_opener(cookies,handler)
t1=time.time()
try:
req=opener.open(self.testurl,timeout=self.timeout)
res=req.read()
res=str(res,encoding='utf8')
usetime=time.time()-t1
if self.testStr in res:
checkedProxyList.append((proxy,usetime))
except Exception as e :
print(e)
def run(self):
self.checkproxy()
if __name__=='__main__':
num=20
thread_num=10
checkThrends=[]
url='YOUR PROXY URL' #提取代理的網(wǎng)站。
req=request.urlopen(url).read()
req=str(req,encoding='utf-8')
list=req.split('\r\n') #網(wǎng)站返回的是字符串格式,用'\r\n'進(jìn)行分割
rawProxyList=list
print('get raw proxy')
for i in rawProxyList:
print(i)
# s=proxycheck_test(rawProxyList)
batch_size=int((len(rawProxyList)+thread_num-1)/thread_num)
print(batch_size)
for i in range(thread_num):
t=proxycheck(rawProxyList[batch_size*i:batch_size*(i+1)])
checkThrends.append(t)
for i in range(checkThrends.__len__()):
checkThrends[i].start()
for i in range(checkThrends.__len__()):
checkThrends[i].join()
print(checkedProxyList.__len__(),' useful proxy is find')
for i in checkedProxyList:
print(i)
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python描述數(shù)據(jù)結(jié)構(gòu)學(xué)習(xí)之哈夫曼樹篇
這篇文章主要給大家介紹了關(guān)于Python描述數(shù)據(jù)結(jié)構(gòu)學(xué)習(xí)之哈夫曼樹篇的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
python 回調(diào)函數(shù)和回調(diào)方法的實現(xiàn)分析
python smtplib模塊自動收發(fā)郵件功能(二)
Python中json.dumps()函數(shù)使用和示例

