python如何基于redis实现ip代理池

所属分类: 脚本专栏 / python 阅读数: 1392
收藏 0 赞 0 分享

这篇文章主要介绍了python如何基于redis实现ip代理池,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

使用apscheduler库定时爬取ip,定时检测ip删除ip,做了2层检测,第一层爬取后放入redis——db0进行检测,成功的放入redis——db1再次进行检测,确保获取的代理ip的可用性

import requests, redis
import pandas
import random

from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
import logging

db_conn = redis.ConnectionPool(host="*.*.*.*", port=6379, password="123456")
redis_conn_0 = redis.Redis(connection_pool=db_conn, max_connections=10,db=0)
redis_conn_1 = redis.Redis(connection_pool=db_conn, max_connections=10,db=1)


# 删除redis数据库里的ip
def remove_ip(ip,redis_conn):
  redis_conn.zrem("IP", ip)
  print("已删除 %s..." % ip)


# 获取redis数据库里一共有多少ip
def get_ip_num(redis_conn):
  num = redis_conn.zcard("IP")
  return num


# 获取ip的端口
def get_port(ip,redis_conn):
  port = redis_conn.zscore("IP", ip)
  port = str(port).replace(".0", "")
  return port


# 添加ip和端口到数据库里
def add_ip(ip, port,redis_conn):
  # nx: 不要更新已有的元素。总是添加新的元素,只有True,False
  redis_conn.zadd("IP", {ip: port}, nx=55)
  print("已添加 %s %s...ok" % (ip, port))


# 列出所有的ip
def get_all_ip(redis_conn):
  all_ip = redis_conn.zrange("IP", 0, -1)
  return all_ip


# 随机获取一个ip
def get_random_ip(redis_conn):
  end_num = get_ip_num(redis_conn)
  num = random.randint(0, end_num)
  random_ip = redis_conn.zrange("IP", num, num)
  if not random_ip:
    return "",""
  random_ip = str(random_ip[0]).replace("b", '').replace("'", "")
  port = get_port(random_ip,redis_conn)
  return random_ip, port


# 获取代理ip
def spider_ip(x,redis_conn):
  print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x)
  for p in range(1, 20):
    res = pandas.read_html("http://www.89ip.cn/index_{}.html".format(p))
    # print(res)
    # print(type(res[0]))
    for i in range(len(res[0])):
      ip = res[0].iloc[i, 0]
      port = res[0].iloc[i, 1]
      print("ip", ip)
      print("port", port)
      add_ip(str(ip), str(port),redis_conn)


logging.basicConfig(level=logging.INFO,
          format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
          datefmt='%Y-%m-%d %H:%M:%S',
          filename='log1.txt',
          filemode='a')


def aps_detection_ip(x,redis_conn):
  print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x)
  res=get_random_ip(redis_conn)
  ip=res[0]
  port=res[1]
  try:
    requests.get("http://www.baidu.com",proxies={'https':'{ip}:{port}'.format(ip=ip,port=port)})
    print("可用",ip,port,res)
    if redis_conn!=redis_conn_1:
      add_ip(str(ip), str(port), redis_conn_1)
  except Exception:
    # ip错误失效就删除
    remove_ip(ip,redis_conn)


scheduler = BlockingScheduler()
scheduler.add_job(func=aps_detection_ip, args=('检测循环任务0',redis_conn_0), trigger='interval', seconds=3, id='aps_detection_ip_task0',max_instances=10)
scheduler.add_job(func=spider_ip, args=('获取循环任务0',redis_conn_0), trigger='interval', seconds=60*60*2, id='spider_ip_task0',max_instances=10)

scheduler.add_job(func=aps_detection_ip, args=('检测循环任务1',redis_conn_1), trigger='interval', seconds=3, id='aps_detection_ip_task1',max_instances=10)

scheduler._logger = logging

# scheduler.start()
if __name__ == '__main__':
  # print(get_ip_num())
  # spider_ip("获取循环任务")
  scheduler.start()
  # aps_detection_ip("检测循环任务")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Python常见加密模块用法分析【MD5,sha,crypt模块】

这篇文章主要介绍了Python常见加密模块用法,结合实例形式较为详细的分析了MD5,sha与crypt模块加密的相关实现方法与操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Python向日志输出中添加上下文信息

这篇文章主要介绍了Python向日志输出中添加上下文信息的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Python实现的简单dns查询功能示例

这篇文章主要介绍了Python实现的简单dns查询功能,结合实例形式分析了Python基于socket模块的dns信息查询实现技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

利用Anaconda完美解决Python 2与python 3的共存问题

Anaconda 是 Python 的一个发行版,如果把 Python 比作 Linux,那么 Anancoda 就是 CentOS 或者 Ubuntu,下面这篇文章主要给大家介绍了利用Anaconda完美解决Python 2与python 3共存问题的相关资料,文中介绍的非常详
收藏 0 赞 0 分享

Python随机读取文件实现实例

这篇文章主要介绍了Python随机读取文件的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

用生成器来改写直接返回列表的函数方法

下面小编就为大家带来一篇用生成器来改写直接返回列表的函数方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

python爬虫入门教程--快速理解HTTP协议(一)

http协议是互联网里面最重要,最基础的协议之一,我们的爬虫需要经常和http协议打交道。下面这篇文章主要给大家介绍了关于python爬虫入门之快速理解HTTP协议的相关资料,文中介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。
收藏 0 赞 0 分享

老生常谈Python进阶之装饰器

下面小编就为大家带来一篇老生常谈Python进阶之装饰器。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

浅谈Python基础之I/O模型

下面小编就为大家带来一篇浅谈Python基础之I/O模型。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

python如何获取服务器硬件信息

这篇文章主要为大家详细介绍了python获取服务器硬件信息的相关代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享
查看更多