溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python 爬蟲IP代理池的實現(xiàn)

發(fā)布時間:2020-08-06 20:54:29 來源:ITPUB博客 閱讀:235 作者:犀牛小牛 欄目:數(shù)據(jù)庫

Python 爬蟲IP代理池的實現(xiàn)


很多時候,如果要多線程的爬取網(wǎng)頁,或者是單純的反爬,我們需要通過代理 IP來進行訪問。下面看看一個基本的實現(xiàn)方法。

代理 IP Python 爬蟲IP代理池的實現(xiàn) 附件.txt 的提取,網(wǎng)上有很多網(wǎng)站都提供這個服務?;旧峡煽啃院豌y子是成正比的。國內(nèi)提供的免費IP基本上都是沒法用的,如果要可靠的代理只能付費;國外稍微好些,有些免費IP還是比較靠譜的。

網(wǎng)上隨便搜索了一下,找了個網(wǎng)頁,本來還想手動爬一些對應的 IP,結果發(fā)現(xiàn)可以直接下載現(xiàn)成的txt文件

下載之后,試試看用不同的代理去爬百度首頁

#!/usr/bin/env python#! -*- coding:utf-8 -*-# Author: Yuan Liimport re,urllib.requestfp=open("c:\\temp\\thebigproxylist-17-12-20.txt",'r')lines=fp.readlines()for ip in lines:    try:            print("當前代理IP "+ip)            proxy=urllib.request.ProxyHandler({"http":ip})            opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandler)            urllib.request.install_opener(opener)            url="http://www.baidu.com"            data=urllib.request.urlopen(url).read().decode('utf-8','ignore')            print("通過")            print("-----------------------------")    except Exception as err:        print(err)        print("-----------------------------")fp.close()

結果如下:

C:\Python36\python.exe C:/Users/yuan.li/Documents/GitHub/Python/Misc/爬蟲/proxy.py當前代理IP 137.74.168.174:80通過-----------------------------當前代理IP 103.28.161.68:8080通過-----------------------------當前代理IP 91.151.106.127:53281HTTP Error 503: Service Unavailable-----------------------------當前代理IP 177.136.252.7:3128<urlopen error [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>-----------------------------當前代理IP 47.89.22.200:80通過-----------------------------當前代理IP 118.69.61.57:8888HTTP Error 503: Service Unavailable-----------------------------當前代理IP 192.241.190.167:8080通過-----------------------------當前代理IP 185.124.112.130:80通過-----------------------------當前代理IP 83.65.246.181:3128通過-----------------------------當前代理IP 79.137.42.124:3128通過-----------------------------當前代理IP 95.0.217.32:8080<urlopen error [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>-----------------------------當前代理IP 104.131.94.221:8080通過

不過上面這種方式只適合比較穩(wěn)定的 IP源,如果IP不穩(wěn)定的話,可能很快對應的文本就失效了,最好可以動態(tài)地去獲取最新的IP地址。很多網(wǎng)站都提供API可以實時地去查詢
還是用剛才的網(wǎng)站,這次我們用 API去調(diào)用,這里需要瀏覽器偽裝一下才能爬取

#!/usr/bin/env python#! -*- coding:utf-8 -*-# Author: Yuan Liimport re,urllib.requestheaders=("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0")opener=urllib.request.build_opener()opener.addheaders=[headers]#安裝為全局urllib.request.install_opener(opener)data=urllib.request.urlopen("http://www.thebigproxylist.com/members/proxy-api.php?output=all&user=list&pass=8a544b2637e7a45d1536e34680e11adf").read().decode('utf8')ippool=data.split('\n')for ip in ippool:    ip=ip.split(',')[0]    try:            print("當前代理IP "+ip)            proxy=urllib.request.ProxyHandler({"http":ip})            opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandler)            urllib.request.install_opener(opener)            url="http://www.baidu.com"            data=urllib.request.urlopen(url).read().decode('utf-8','ignore')            print("通過")            print("-----------------------------")    except Exception as err:        print(err)        print("-----------------------------")fp.close()

結果如下:

C:\Python36\python.exe C:/Users/yuan.li/Documents/GitHub/Python/Misc/爬蟲/proxy.py當前代理IP 213.233.57.134:80HTTP Error 403: Forbidden-----------------------------當前代理IP 144.76.81.79:3128通過-----------------------------當前代理IP 45.55.132.29:53281HTTP Error 503: Service Unavailable-----------------------------當前代理IP 180.254.133.124:8080通過-----------------------------當前代理IP 5.196.215.231:3128HTTP Error 503: Service Unavailable-----------------------------當前代理IP 177.99.175.195:53281HTTP Error 503: Service Unavailable

因為直接 for循環(huán)來按順序讀取文本實在是太慢了,我試著改成多線程來讀取,這樣速度就快多了

#!/usr/bin/env python#! -*- coding:utf-8 -*-# Author: Yuan Liimport threadingimport queueimport re,urllib.request#Number of threadsn_thread = 10#Create queuequeue = queue.Queue()class ThreadClass(threading.Thread):    def __init__(self, queue):        threading.Thread.__init__(self)                

super(ThreadClass, self).__init__()    #Assign thread working with queue        self.queue = queue    def run(self):        while True:        #Get from queue job            host = self.queue.get()            

print (self.getName() + ":" + host)            try:                # print("當前代理IP " + host)                proxy = urllib.request.ProxyHandler({"http": host})                opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)                urllib.request.install_opener(opener)                url = "http://www.baidu.com"                data = urllib.request.urlopen(url).read().decode('utf-8', 'ignore')                print("通過")                print("-----------------------------")            

except Exception as err:                print(err)                

print("-----------------------------")            #signals to queue jo

 

 

 

 

 

 


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI