寫在前面
建立Python爬蟲IP代理池可以提高爬蟲的穩定性和效率,可以有效避免IP被封鎖或限制訪問等問題。
?
下面是建立Python爬蟲IP代理池的詳細步驟和代碼實現:
1. 獲取代理IP
我們可以從一些代理IP網站上獲取免費或付費的代理IP,或者自己租用代理IP服務。這里我們以站大爺代理為例,獲取前10頁的HTTP代理IP地址。
import requests
from scrapy.selector import Selectordef get_proxy_ips():proxy_ips = []for i in range(1, 11):url = 'https://www.zdaye.com/free/'.format(i)headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}res = requests.get(url, headers=headers)selector = Selector(text=res.text)trs = selector.css('#ip_list tr')for tr in trs[1:]:ip = tr.css('td:nth-child(2)::text').extract_first()port = tr.css('td:nth-child(3)::text').extract_first()proxy_ips.append('{}:{}'.format(ip, port))return proxy_ips
2. 檢測代理IP的可用性
獲取到代理IP后,需要對其進行可用性的檢測,篩選出可用性較高的IP地址。這里我們測試以百度為目標網站檢測HTTP代理IP地址的可用性,如果響應碼為200,則表明該IP地址可用。
import requestsdef check_proxy_ip(ip):url = 'http://www.baidu.com'headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}proxies = {'http': 'http://' + ip, 'https': 'https://' + ip}try:res = requests.get(url, headers=headers, proxies=proxies, timeout=10)if res.status_code == 200:return Trueelse:return Falseexcept:return False
3. 將可用的代理IP存儲到池中
將可用的代理IP存儲到一個IP池中,根據需要可以設置IP池的容量和存儲時間。這里我們將可用的IP地址存儲到redis數據庫中。
import redisdef save_proxy_ips():proxy_ips = get_proxy_ips()pool = redis.ConnectionPool(host='localhost', port=6379, db=0)r = redis.Redis(connection_pool=pool)for ip in proxy_ips:if check_proxy_ip(ip):r.sadd('proxy_ip_pool', ip)
4. 在爬蟲程序中使用代理IP池
在爬蟲程序中設置代理IP池,并在請求時隨機選擇一個可用的代理IP地址進行訪問。這里我們使用requests庫和random模塊實現。
import requests
import redis
import randomdef get_my_ip():url = 'http://httpbin.org/ip'res = requests.get(url)return res.json()['origin']def get_random_proxy():pool = redis.ConnectionPool(host='localhost', port=6379, db=0)r = redis.Redis(connection_pool=pool)ip = r.srandmember('proxy_ip_pool')return ip.decode('utf-8')# 隨機選擇代理IP進行訪問
def crawl(url):proxy = {'http': 'http://'+get_random_proxy(), 'https': 'https://'+get_random_proxy()}headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}try:res = requests.get(url, headers=headers, proxies=proxy, timeout=10)if res.status_code == 200:return res.textelse:return Noneexcept:return None
總結
需要注意的是,代理IP池的建立和使用需要注意IP的有效性和時效性,及時更新池中的IP地址,以保證代理IP的可用性。同時,在使用代理IP時需要遵守相關法律法規和網站的使用協議,不得用于非法活動。