Python构建代理ip池
生活随笔
收集整理的這篇文章主要介紹了
Python构建代理ip池
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 概述
- 提供免費代理的網站
- 代碼
- 導包
- 網站頁面的url
- ip地址
- 檢測
- 整理
- 必要參數
- 總代碼
- 總結
概述
用爬蟲時,大部分網站都有一定的反爬措施,有些網站會限制每個 IP 的訪問速度或訪問次數,超出了它的限制你的 IP 就會被封掉。對于訪問速度的處理比較簡單,只要間隔一段時間爬取一次就行了,避免頻繁訪問;而對于訪問次數,就需要使用代理 IP 來幫忙了,使用多個代理 IP 輪換著去訪問目標網址可以有效地解決問題。
目前網上有很多的代理服務網站提供代理服務,也提供一些免費的代理,但可用性較差,如果需求較高可以購買付費代理,可用性較好。
因此我們可以自己構建代理池,從各種代理服務網站中獲取代理 IP,并檢測其可用性(使用一個穩定的網址來檢測,最好是自己將要爬取的網站),再保存到數據庫中,需要使用的時候再調用。
提供免費代理的網站
| 66代理 | http://www.66ip.cn/ |
| 西刺代理 | https://www.xicidaili.com |
| 全網代理 | http://www.goubanjia.com |
| 云代理 | http://www.ip3366.net |
| IP海 | http://www.iphai.com |
| 快代理 | https://www.kuaidaili.com |
| 免費代理IP庫 | http://ip.jiangxianli.com |
| 小幻代理 | https://ip.ihuan.me/ |
本次使用的案例是小幻代理
代碼
導包
import loguru, requests, random, time # 發送請求,記錄日志,等 from lxml import etree # 分析數據 from concurrent.futures import ThreadPoolExecutor # 線程池網站頁面的url
由于小幻代理的每個頁面的url沒有規律,所以需要一一獲取
def get_url(): # 得到存放ip地址的網頁print("正在獲取ip池", ",不要著急!")for i in range(random.randint(10, 20)): # 爬取隨機頁數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)breakhtml = 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網址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("//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的,那么還是使用本機的ip,如果請求的ip是http類型的,那么代理的ip一定要是http的,前面不能寫成https,否則使用本機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標識temp_ip.append(ip) # 符合條件的添加,不符合條件的拋棄整理
def set_ip(url) -> "動態構建ip池": # 要傳入需要爬取網頁的urltry:f = open('./app/ip.txt', "r")for j in eval(f.read()):temp_ip.append(j)f.close()except Exception as e:print("沒有ip,正在構造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字符串,同時利用字典去重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的,那么還是使用本機的ip,如果請求的ip是http類型的,那么代理的ip一定要是http的,前面不能寫成https,否則使用本機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標識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 proxyelse:set_ip(url=url)必要參數
# 參數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 ThreadPoolExecutordef get_url(): # 得到存放ip地址的網頁print("正在獲取ip池", ",不要著急!")for i in range(random.randint(10, 20)): # 爬取隨機頁數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)breakhtml = 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網址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("//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) -> "動態構建ip池": # 要傳入需要爬取網頁的urltry:f = open('./app/ip.txt', "r")for j in eval(f.read()):temp_ip.append(j)f.close()except Exception as e:print("沒有ip,正在構造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字符串,同時利用集合去重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的,那么還是使用本機的ip,如果請求的ip是http類型的,那么代理的ip一定要是http的,前面不能寫成https,否則使用本機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標識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 proxyelse:set_ip(url=url)# 參數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") # 得到代理ipprint(proxy)總結
如果安裝了數據庫的話,可以使用數據庫存儲得到的ip,代碼中使用的是本地的文件存儲數據,同時,要盡量避免本機ip被封
總結
以上是生活随笔為你收集整理的Python构建代理ip池的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端学习(1185):数据响应式
- 下一篇: 计算机二级Python公共基础部分