用python構(gòu)建IP代理池詳解
概述
用爬蟲時(shí),大部分網(wǎng)站都有一定的反爬措施,有些網(wǎng)站會(huì)限制每個(gè) IP 的訪問速度或訪問次數(shù),超出了它的限制你的 IP 就會(huì)被封掉。對(duì)于訪問速度的處理比較簡(jiǎn)單,只要間隔一段時(shí)間爬取一次就行了,避免頻繁訪問;而對(duì)于訪問次數(shù),就需要使用代理 IP 來(lái)幫忙了,使用多個(gè)代理 IP 輪換著去訪問目標(biāo)網(wǎng)址可以有效地解決問題。
目前網(wǎng)上有很多的代理服務(wù)網(wǎng)站提供代理服務(wù),也提供一些免費(fèi)的代理,但可用性較差,如果需求較高可以購(gòu)買付費(fèi)代理,可用性較好。
因此我們可以自己構(gòu)建代理池,從各種代理服務(wù)網(wǎng)站中獲取代理 IP,并檢測(cè)其可用性(使用一個(gè)穩(wěn)定的網(wǎng)址來(lái)檢測(cè),最好是自己將要爬取的網(wǎng)站),再保存到數(shù)據(jù)庫(kù)中,需要使用的時(shí)候再調(diào)用。
提供免費(fèi)代理的網(wǎng)站
廠商名稱 | 地址 |
---|---|
66代理 | http://www.66ip.cn/ |
西刺代理 | https://www.xicidaili.com |
全網(wǎng)代理 | http://www.goubanjia.com |
云代理 | http://www.ip3366.net |
IP海 | http://www.iphai.com |
快代理 | https://www.kuaidaili.com |
免費(fèi)代理IP庫(kù) | http://ip.jiangxianli.com |
小幻代理 | https://ip.ihuan.me/ |
代碼
導(dǎo)包
import loguru, requests, random, time # 發(fā)送請(qǐng)求,記錄日志,等 from lxml import etree # 分析數(shù)據(jù) from concurrent.futures import ThreadPoolExecutor # 線程池
網(wǎng)站頁(yè)面的url
由于小幻代理的每個(gè)頁(yè)面的url沒有規(guī)律,所以需要一一獲取
def get_url(): # 得到存放ip地址的網(wǎng)頁(yè) print("正在獲取ip池", ",不要著急!") for i in range(random.randint(10, 20)): # 爬取隨機(jī)頁(yè)數(shù) time.sleep(1) if i == 0: url = "https://ip.ihuan.me/" else: url = url_list[-1] try: resp = requests.get(url=url, headers=headers_test, timeout=10) except Exception as e: print(e) break html = etree.HTML(resp.text) ul = html.xpath('//ul[@class="pagination"]') ul_num = html.xpath('//ul[@class="pagination"]/li') for j in range(len(ul_num)): if j != 0 and j != len(ul_num) - 1: a = ul[0].xpath(f"./li[{j}+1]/a/@href")[0] url_list.append("https://ip.ihuan.me/" + a) # 得到許多的代理ip網(wǎng)址 loguru.logger.info(f"over,{url}")
ip地址
def get_ip(): for i in url_list: time.sleep(1) resp = requests.get(url=i, headers=headers) html = etree.HTML(resp.text) td = html.xpath("http://tbody/tr") for i in td: ip = i.xpath("./td[1]//text()")[0] # 地址 pt = i.xpath("./td[2]//text()")[0] # 端口 tp = "http" if i.xpath("./td[5]//text()")[0] == "不支持" else "https" # 訪問類型 ip_list.append({"type": tp, "proxy": f"{ip}:{pt}"}) loguru.logger.info("ip地址獲取完成")
檢測(cè)
def test_ip(ip): proxy_test = { "http": f"{ip}", "https": f"{ip}" # 注意:如果請(qǐng)求的ip是https類型的,但代理的ip是只支持http的,那么還是使用本機(jī)的ip,如果請(qǐng)求的ip是http類型的,那么代理的ip一定要是http的,前面不能寫成https,否則使用本機(jī)IP地址 } resp = requests.get(url=url_test, headers=headers, proxies=proxy_test, timeout=6) if resp.json()["origin"] == ip.split(":")[0]: ip = {"type": url.strip(":")[0], "proxy": ip} # 格式化ip,便于后期處理,是的其有http/https標(biāo)識(shí) temp_ip.append(ip) # 符合條件的添加,不符合條件的拋棄
整理
def set_ip(url) -> "動(dòng)態(tài)構(gòu)建ip池": # 要傳入需要爬取網(wǎng)頁(yè)的url try: f = open('./app/ip.txt', "r") for j in eval(f.read()): temp_ip.append(j) f.close() except Exception as e: print("沒有ip,正在構(gòu)造ip池,請(qǐng)稍等") if not temp_ip: # 判斷是否有ip地址 print("沒有ip地址,正在獲取") get_url() else: for i in temp_ip: ip_list.append(i) # 將已有的ip添加到測(cè)試ip中 temp_ip.clear() get_ip() # 得到大量ip地址 with open('./app/ip.txt', "w") as file: file.write(ip_list) ip_able = list(set(j["proxy"] for j in ip_list if j["type"] == url.split(":")[0])) # 存放符合要求的ip字符串,同時(shí)利用字典去重 url_test = "http://httpbin.org/ip" if url.split(":")[0] == "http" else "" # 測(cè)試ip地址是否有用 def test_ip(ip): proxy_test = { "http": f"{ip}", "https": f"{ip}" # 注意:如果請(qǐng)求的ip是https類型的,但代理的ip是只支持http的,那么還是使用本機(jī)的ip,如果請(qǐng)求的ip是http類型的,那么代理的ip一定要是http的,前面不能寫成https,否則使用本機(jī)IP地址 } resp = requests.get(url=url_test, headers=headers, proxies=proxy_test, timeout=6) if resp.json()["origin"] == ip.split(":")[0]: ip = {"type": url.strip(":")[0], "proxy": ip} # 格式化ip,便于后期處理,是的其有http/https標(biāo)識(shí) temp_ip.append(ip) # 符合條件的添加,不符合條件的拋棄 with ThreadPoolExecutor(50) as pool: # 使用多線程測(cè)試 pool.map(test_ip, ip_able) pool.join() print("測(cè)試完畢") if temp_ip: i = random.choice(temp_ip) proxy = { "http": f"{i['proxy']}", "https": f"{i['proxy']}" } return proxy else: set_ip(url=url)
必要參數(shù)
# 參數(shù) headers = { 'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" } headers_test = { 'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36", "accept-encoding": "gzip, deflate, br", "cookie": "Hm_lvt_8ccd0ef22095c2eebfe4cd6187dea829=1642389014,1642412091", "Referer": "https://ip.ihuan.me/" } url_list, ip_list, temp_ip = ["https://ip.ihuan.me/"], [], [] # 存放url, 存放ip地址, 有用的ip地址
總代碼
import loguru, requests, random, time from lxml import etree from concurrent.futures import ThreadPoolExecutor def get_url(): # 得到存放ip地址的網(wǎng)頁(yè) print("正在獲取ip池", ",不要著急!") for i in range(random.randint(10, 20)): # 爬取隨機(jī)頁(yè)數(shù) time.sleep(1) if i == 0: url = "https://ip.ihuan.me/" else: url = url_list[-1] try: resp = requests.get(url=url, headers=headers_test, timeout=10) except Exception as e: print(e) break html = etree.HTML(resp.text) ul = html.xpath('//ul[@class="pagination"]') ul_num = html.xpath('//ul[@class="pagination"]/li') for j in range(len(ul_num)): if j != 0 and j != len(ul_num) - 1: a = ul[0].xpath(f"./li[{j}+1]/a/@href")[0] url_list.append("https://ip.ihuan.me/" + a) # 得到許多的代理ip網(wǎng)址 loguru.logger.info(f"over,{url}") def get_ip(): for i in url_list: time.sleep(1) resp = requests.get(url=i, headers=headers) html = etree.HTML(resp.text) td = html.xpath("http://tbody/tr") for i in td: ip = i.xpath("./td[1]//text()")[0] # 地址 pt = i.xpath("./td[2]//text()")[0] # 端口 tp = "http" if i.xpath("./td[5]//text()")[0] == "不支持" else "https" # 訪問類型 ip_list.append({"type": tp, "proxy": f"{ip}:{pt}"}) loguru.logger.info("ip地址獲取完成") def set_ip(url) -> "動(dòng)態(tài)構(gòu)建ip池": # 要傳入需要爬取網(wǎng)頁(yè)的url try: f = open('./app/ip.txt', "r") for j in eval(f.read()): temp_ip.append(j) f.close() except Exception as e: print("沒有ip,正在構(gòu)造ip池,請(qǐng)稍等") if not temp_ip: # 判斷是否有ip地址 print("沒有ip地址,正在獲取") get_url() else: for i in temp_ip: ip_list.append(i) # 將已有的ip添加到測(cè)試ip中 temp_ip.clear() get_ip() # 得到大量ip地址 with open('./app/ip.txt', "w") as file: file.write(ip_list) ip_able = list(set(j["proxy"] for j in ip_list if j["type"] == url.split(":")[0])) # 存放符合要求的ip字符串,同時(shí)利用集合去重 url_test = "http://httpbin.org/ip" if url.split(":")[0] == "http" else "" # 測(cè)試ip地址是否有用 def test_ip(ip): proxy_test = { "http": f"{ip}", "https": f"{ip}" # 注意:如果請(qǐng)求的ip是https類型的,但代理的ip是只支持http的,那么還是使用本機(jī)的ip,如果請(qǐng)求的ip是http類型的,那么代理的ip一定要是http的,前面不能寫成https,否則使用本機(jī)IP地址 } resp = requests.get(url=url_test, headers=headers, proxies=proxy_test, timeout=6) if resp.json()["origin"] == ip.split(":")[0]: ip = {"type": url.strip(":")[0], "proxy": ip} # 格式化ip,便于后期處理,是的其有http/https標(biāo)識(shí) temp_ip.append(ip) # 符合條件的添加,不符合條件的拋棄 with ThreadPoolExecutor(50) as pool: # 使用多線程測(cè)試 pool.map(test_ip, ip_able) pool.join() print("測(cè)試完畢") if temp_ip: i = random.choice(temp_ip) proxy = { "http": f"{i['proxy']}", "https": f"{i['proxy']}" } return proxy else: set_ip(url=url) # 參數(shù) headers = { 'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" } headers_test = { 'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36", "accept-encoding": "gzip, deflate, br", "cookie": "Hm_lvt_8ccd0ef22095c2eebfe4cd6187dea829=1642389014,1642412091", "Referer": "https://ip.ihuan.me/" } url_list, ip_list, temp_ip = ["https://ip.ihuan.me/"], [], [] # 存放url, 存放ip地址, 有用的ip地址 if __name__ == '__main__': proxy = set_ip(url="https://www.baidu.com") # 得到代理ip print(proxy)
總結(jié)
如果安裝了數(shù)據(jù)庫(kù)的話,可以使用數(shù)據(jù)庫(kù)存儲(chǔ)得到的ip,代碼中使用的是本地的文件存儲(chǔ)數(shù)據(jù),同時(shí),要盡量避免本機(jī)ip被封
到此這篇關(guān)于用python構(gòu)建IP代理池詳解的文章就介紹到這了,更多相關(guān)python IP代理池詳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python 尋找優(yōu)化使成本函數(shù)最小的最優(yōu)解的方法
這篇文章主要介紹了python 尋找優(yōu)化使成本函數(shù)最小的最優(yōu)解的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2017-12-12使用Python簡(jiǎn)單的實(shí)現(xiàn)樹莓派的WEB控制
這篇文章主要介紹了使用Python簡(jiǎn)單的實(shí)現(xiàn)樹莓派的WEB控制的相關(guān)資料,需要的朋友可以參考下2016-02-02Pandas的Series結(jié)構(gòu)及常用操作實(shí)例
這篇文章主要介紹了Pandas的Series結(jié)構(gòu)及常用操作實(shí)例,Series序列,是一種一維的結(jié)構(gòu),類似于一維列表和ndarray中的一維數(shù)組,但是功能比他們要更為強(qiáng)大,Series由兩部分組成:索引index和數(shù)值values,需要的朋友可以參考下2023-07-07Pycharm學(xué)習(xí)教程(5) Python快捷鍵相關(guān)設(shè)置
這篇文章主要為大家詳細(xì)介紹了最全的Pycharm學(xué)習(xí)教程第五篇,Python快捷鍵相關(guān)設(shè)置,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05