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

yipeiwu_com6年前Python基础

这篇文章主要介绍了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设计】。

相关文章

python实现带错误处理功能的远程文件读取方法

本文实例讲述了python实现带错误处理功能的远程文件读取方法。分享给大家供大家参考。具体如下: import socket, sys, time host = sys.argv[1...

Python requests发送post请求的一些疑点

Python requests发送post请求的一些疑点

前言 在Python爬虫中,使用requests发送请求,访问指定网站,是常见的做法。一般是发送GET请求或者POST请求,对于GET请求没有什么好说的,而发送POST请求,有很多朋友不...

解决Python3下map函数的显示问题

map函数是Python里面比较重要的函数,设计灵感来自于函数式编程。Python官方文档中是这样解释map函数的: map(function, iterable, ...) Retu...

在交互式环境中执行Python程序过程详解

在交互式环境中执行Python程序过程详解

前言 相信接触过Python的伙伴们都知道运行Python脚本程序的方式有多种,目前主要的方式有:交互式环境运行、命令行窗口运行、开发工具上运行等,其中在不同的操作平台上还互不相同。今天...

Python 文件管理实例详解

本文实例讲述了Python 文件管理的方法。分享给大家供大家参考,具体如下: 一、Python中的文件管理 文件管理是很多应用程序的基本功能和重要组成部分。Python可以使文件管理极其...