Python爬虫IP代理池的建立和使用

写在前面

建立Python爬虫IP代理池可以提高爬虫的稳定性和效率,可以有效避免IP被封锁或限制访问等问题。

下面是建立Python爬虫IP代理池的详细步骤和代码实现:

1. 获取代理IP

我们可以从一些代理IP网站上获取免费或付费的代理IP,或者自己租用代理IP服务。这里我们以站大爷代理为例,获取前10页的HTTP代理IP地址。

python 复制代码
import requests
from scrapy.selector import Selector

def 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地址可用。

python 复制代码
import requests

def 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 True
        else:
            return False
    except:
        return False
3. 将可用的代理IP存储到池中

将可用的代理IP存储到一个IP池中,根据需要可以设置IP池的容量和存储时间。这里我们将可用的IP地址存储到redis数据库中。

python 复制代码
import redis

def 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模块实现。

python 复制代码
import requests
import redis
import random

def 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.text
        else:
            return None
    except:
        return None
总结

需要注意的是,代理IP池的建立和使用需要注意IP的有效性和时效性,及时更新池中的IP地址,以保证代理IP的可用性。同时,在使用代理IP时需要遵守相关法律法规和网站的使用协议,不得用于非法活动。

相关推荐
Narutolxy27 分钟前
Python 单元测试:深入理解与实战应用20240919
python·单元测试·log4j
Amo Xiang1 小时前
2024 Python3.10 系统入门+进阶(十五):文件及目录操作
开发语言·python
liangbm31 小时前
数学建模笔记——动态规划
笔记·python·算法·数学建模·动态规划·背包问题·优化问题
B站计算机毕业设计超人1 小时前
计算机毕业设计Python+Flask微博情感分析 微博舆情预测 微博爬虫 微博大数据 舆情分析系统 大数据毕业设计 NLP文本分类 机器学习 深度学习 AI
爬虫·python·深度学习·算法·机器学习·自然语言处理·数据可视化
羊小猪~~1 小时前
深度学习基础案例5--VGG16人脸识别(体验学习的痛苦与乐趣)
人工智能·python·深度学习·学习·算法·机器学习·cnn
waterHBO3 小时前
python 爬虫 selenium 笔记
爬虫·python·selenium
编程零零七4 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
AIAdvocate6 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼6 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
FreakStudio8 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
python·嵌入式·面向对象·电子diy