用python構(gòu)建IP代理池詳解
概述
用爬蟲時(shí),大部分網(wǎng)站都有一定的反爬措施,有些網(wǎng)站會限制每個(gè) IP 的訪問速度或訪問次數(shù),超出了它的限制你的 IP 就會被封掉。對于訪問速度的處理比較簡單,只要間隔一段時(shí)間爬取一次就行了,避免頻繁訪問;而對于訪問次數(shù),就需要使用代理 IP 來幫忙了,使用多個(gè)代理 IP 輪換著去訪問目標(biāo)網(wǎng)址可以有效地解決問題。
目前網(wǎng)上有很多的代理服務(wù)網(wǎng)站提供代理服務(wù),也提供一些免費(fèi)的代理,但可用性較差,如果需求較高可以購買付費(fèi)代理,可用性較好。
因此我們可以自己構(gòu)建代理池,從各種代理服務(wù)網(wǎng)站中獲取代理 IP,并檢測其可用性(使用一個(gè)穩(wěn)定的網(wǎng)址來檢測,最好是自己將要爬取的網(wǎng)站),再保存到數(shù)據(jù)庫中,需要使用的時(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庫 | http://ip.jiangxianli.com |
| 小幻代理 | https://ip.ihuan.me/ |
代碼
導(dǎo)包
import loguru, requests, random, time # 發(fā)送請求,記錄日志,等 from lxml import etree # 分析數(shù)據(jù) from concurrent.futures import ThreadPoolExecutor # 線程池
網(wǎng)站頁面的url
由于小幻代理的每個(gè)頁面的url沒有規(guī)律,所以需要一一獲取
def get_url(): # 得到存放ip地址的網(wǎng)頁
print("正在獲取ip池", ",不要著急!")
for i in range(random.randint(10, 20)): # 爬取隨機(jī)頁數(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地址獲取完成")
檢測
def test_ip(ip):
proxy_test = {
"http": f"{ip}",
"https": f"{ip}"
# 注意:如果請求的ip是https類型的,但代理的ip是只支持http的,那么還是使用本機(jī)的ip,如果請求的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)識
temp_ip.append(ip) # 符合條件的添加,不符合條件的拋棄
整理
def set_ip(url) -> "動態(tài)構(gòu)建ip池": # 要傳入需要爬取網(wǎng)頁的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池,請稍等")
if not temp_ip: # 判斷是否有ip地址
print("沒有ip地址,正在獲取")
get_url()
else:
for i in temp_ip:
ip_list.append(i) # 將已有的ip添加到測試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 "" # 測試ip地址是否有用
def test_ip(ip):
proxy_test = {
"http": f"{ip}",
"https": f"{ip}"
# 注意:如果請求的ip是https類型的,但代理的ip是只支持http的,那么還是使用本機(jī)的ip,如果請求的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)識
temp_ip.append(ip) # 符合條件的添加,不符合條件的拋棄
with ThreadPoolExecutor(50) as pool: # 使用多線程測試
pool.map(test_ip, ip_able)
pool.join()
print("測試完畢")
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)頁
print("正在獲取ip池", ",不要著急!")
for i in range(random.randint(10, 20)): # 爬取隨機(jī)頁數(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) -> "動態(tài)構(gòu)建ip池": # 要傳入需要爬取網(wǎng)頁的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池,請稍等")
if not temp_ip: # 判斷是否有ip地址
print("沒有ip地址,正在獲取")
get_url()
else:
for i in temp_ip:
ip_list.append(i) # 將已有的ip添加到測試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 "" # 測試ip地址是否有用
def test_ip(ip):
proxy_test = {
"http": f"{ip}",
"https": f"{ip}"
# 注意:如果請求的ip是https類型的,但代理的ip是只支持http的,那么還是使用本機(jī)的ip,如果請求的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)識
temp_ip.append(ip) # 符合條件的添加,不符合條件的拋棄
with ThreadPoolExecutor(50) as pool: # 使用多線程測試
pool.map(test_ip, ip_able)
pool.join()
print("測試完畢")
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ù)庫的話,可以使用數(shù)據(jù)庫存儲得到的ip,代碼中使用的是本地的文件存儲數(shù)據(jù),同時(shí),要盡量避免本機(jī)ip被封
到此這篇關(guān)于用python構(gòu)建IP代理池詳解的文章就介紹到這了,更多相關(guān)python IP代理池詳內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Python參數(shù)解析器argparse的應(yīng)用場景
這篇文章主要介紹了關(guān)于Python參數(shù)解析器argparse的應(yīng)用場景,argparse 模塊使編寫用戶友好的命令行界面變得容易,程序定義了所需的參數(shù),而 argparse 將找出如何從 sys.argv 中解析這些參數(shù),需要的朋友可以參考下2023-08-08
Python設(shè)置matplotlib.plot的坐標(biāo)軸刻度間隔以及刻度范圍
這篇文章主要介紹了Python設(shè)置matplotlib.plot的坐標(biāo)軸刻度間隔以及刻度范圍,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-06-06
python開發(fā)利器之ulipad的使用實(shí)踐
Ulipad是一個(gè)國人limodou編寫的專業(yè)Python編輯器,它基于wxpython開發(fā)的GUI(圖形化界面)。下面這篇文章主要介紹了python開發(fā)利器之ulipad的使用實(shí)踐,文中介紹的非常詳細(xì),對大家具有一定的參考價(jià)值,需要的朋友們下面來一起看看吧。2017-03-03
Django使用redis緩存服務(wù)器的實(shí)現(xiàn)代碼示例
這篇文章主要介紹了Django使用redis緩存服務(wù)器的實(shí)現(xiàn)代碼示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
python?sklearn數(shù)據(jù)預(yù)處理之?dāng)?shù)據(jù)縮放詳解
數(shù)據(jù)的預(yù)處理是數(shù)據(jù)分析,或者機(jī)器學(xué)習(xí)訓(xùn)練前的重要步驟,這篇文章主要為大家詳細(xì)介紹了sklearn數(shù)據(jù)預(yù)處理中數(shù)據(jù)縮放的相關(guān)知識,感興趣的小伙伴可以學(xué)習(xí)一下2023-10-10

