Scrapy-从数据库取出IP并判断是否可用

本文介绍了一个Python实现的IP代理池有效性检查系统。该系统使用pymysql连接数据库,通过requests库验证代理IP是否有效。具体操作包括从数据库中随机获取IP,通过尝试访问百度来测试IP的有效性,并在无效时从数据库中删除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import pymysql
import requests

conn = pymysql.connect(host="localhost",user="root",passwd="root",db="CDL",charset="utf8")
cursor = conn.cursor()
class IpUtils(object):

    # 删除无效ip
    def delete_ip(self,ip):
        sql ="delete from xiciproxy where ip='{0}'".format(ip)
        cursor.execute(sql)
        conn.commit()
        return True

    # 判断ip是否可用
    def judge_ip(self,type,ip,port):
        http_url ="http://www.baidu.com"
        proxy_url ="{0}://{1}:{2}".format(type,ip,port)
        print("url:"+ proxy_url)
        try:
            proxy_dict = {
                type: proxy_url, # type 为https 或者http 数据库存储的
            }
            response = requests.get(http_url,proxies=proxy_dict)
        exceptExceptionase:
            self.delete_ip(ip)
            print("invalid ip and port")
            return False
            code = response.status_code
            if code >=200 and code <300:
                print("effective ip")
                return True
        else:
            print("invalid ip and port")
            self.delete_ip(ip)
            return False
    # 随机获取IP
    def get_random_ip(self):
        random_sql ="""
            SELECT type, ip, port FROM xiciproxy
            ORDER BY RAND()
            LIMIT 1
        """
        result = cursor.execute(random_sql)
        for ip_info in cursor.fetchall():
            type = ip_info[0]
            ip = ip_info[1]
            port = ip_info[2]
            judge_re =self.judge_ip(type,ip,port)
            ifjudge_re:
            return"{0}://{1}:{2}".format(type,ip,port)
        else:
            return self.get_random_ip()
if__name__ =="__main__":
    Ip = IpUtils()
    print(Ip.get_random_ip())

2020考研打卡第二十天,星辰之变,骄阳岂是终点。

人生不如意十之八九,我怎么能放弃呢,老子一定要做大做强!!!

转载于:https://www.cnblogs.com/chengdalei/p/10780580.html

`Scrapy-ProxyMiddleware` 是一个用于Scrapy框架的中间件插件,它允许你在Scrapy爬虫中动态地使用代理IP。这个中间件主要用于解决网络请求过程中可能遇到的IP限制或反爬机制。以下是使用`Scrapy-ProxyMiddleware`获取和使用的步骤: 1. **安装与配置**: - 安装 `scrapy-proxies-middleware`:`pip install scrapy-proxies-middleware` - 在`settings.py`文件中启用中间件:添加 `'scrapy_proxies.middlewares.ScrapyProxiesMiddleware'` 到 `DOWNLOADER_MIDDLEWARES` 中。 2. **设置代理源**: - 可以从文件、数据库或API获取代理IP。例如,你可以创建一个文本文件,每一行包含一个代理IP地址(格式通常是 `http://proxy_ip:port` 或 `https://proxy_ip:port`)。 - 通过中间件配置文件 `middlewares.py`,定义代理IP的获取方法,比如从本地文件读取: ```python class MyCustomProxyMiddleware(ScrapyProxiesMiddleware): def get_proxy(self): with open('proxies.txt', 'r') as f: return f.readline().strip() ``` 3. **使用代理**: - 在`Spider`类的`start_requests()`方法中,设置每个请求的代理: ```python class MySpider(scrapy.Spider): def start_requests(self): proxy_url = self.settings.get('PROXY_URL') yield scrapy.Request(url=self.start_urls[0], proxies={'http': proxy_url, 'https': proxy_url}, meta={'proxy_type': 'http'}) ``` 4. **注意事项**: - 自动切换代理IP:中间件通常支持轮询、随机选择或固定顺序等方式切换代理IP,可以配置`change_proxy_interval`等参数。 - 错误处理:如果代理不可用或无效,中间件会自动回退到下一个代理。 通过以上步骤,`Scrapy-ProxyMiddleware`就能帮助你在一个爬虫项目中有效地管理和使用代理IP
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值