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

 更新时间:2020年01月17日 10:32:53   作者:Maple_feng  
这篇文章主要介绍了python如何基于redis实现ip代理池,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

这篇文章主要介绍了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("检测循环任务")

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

相关文章

  • Opencv实现眼睛控制鼠标的实践

    Opencv实现眼睛控制鼠标的实践

    本文主要介绍了Opencv实现眼睛控制鼠标的实践,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • Python中Collections模块的Counter容器类使用教程

    Python中Collections模块的Counter容器类使用教程

    Counter是Python标准库提供的一个非常有用的容器,可以用来对序列中出现的各个元素进行计数,下面就来一起看一下Python中Collections模块的Counter容器类使用教程
    2016-05-05
  • 关于Python网络爬虫框架scrapy

    关于Python网络爬虫框架scrapy

    这篇文章主要介绍了关于Python网络爬虫框架scrapy,爬虫框架是实现爬虫功能的一个软件结构和功能组件的集合,需要的朋友可以参考下
    2023-04-04
  • Python并行库joblib之delayed函数与Parallel函数详解

    Python并行库joblib之delayed函数与Parallel函数详解

    这篇文章主要介绍了Python并行库joblib之delayed函数与Parallel函数详解,Joblib就是一个可以简单地将Python代码转换为并行计算模式的软件包,它可非常简单并行我们的程序,从而提高计算速度,需要的朋友可以参考下
    2023-08-08
  • 解决新django中的path不能使用正则表达式的问题

    解决新django中的path不能使用正则表达式的问题

    今天小编就为大家分享一篇解决新django中的path不能使用正则表达式的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-12-12
  • 如何使用 Python Pandas 更新行和列

    如何使用 Python Pandas 更新行和列

    这篇文章主要介绍了使用 Python Pandas 更新行和列的方法,在整篇文章中,我们将使用我们现在要创建的数据框,这将使大家了解更新数据操作,在此之后,大家可以将这些方法应用于自己的数据,需要的朋友可以参考下
    2023-03-03
  • 如何在Python中引入和使用浏览器驱动

    如何在Python中引入和使用浏览器驱动

    本文介绍了如何在Python中引入和使用浏览器驱动,主要步骤包括安装Selenium库、下载并配置浏览器驱动路径、编写Python代码启动浏览器以及结束操作后关闭浏览器
    2025-01-01
  • Python中try excpet BaseException(异常处理捕获)的使用

    Python中try excpet BaseException(异常处理捕获)的使用

    本文主要介绍了Python中try excpet BaseException(异常处理捕获)的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-03-03
  • Python打包为exe详细教程

    Python打包为exe详细教程

    今天给大家介绍如何用Python打包exe,文中有非常详细的教程,对正在学习python的小伙伴们有很好地帮助,需要的朋友可以参考下
    2021-05-05
  • pandas 透视表中文字段排序方法

    pandas 透视表中文字段排序方法

    今天小编就为大家分享一篇pandas 透视表中文字段排序方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-11-11

最新评论