python如何基于redis实现ip代理池
作者:Maple_feng 发布时间:2022-11-05 20:49:08
标签: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("检测循环任务")
来源:https://www.cnblogs.com/angelyan/p/12157374.html


猜你喜欢
- 如何最准确地统计在线用户数?我们推荐的这个程序据说是目前最好的在线用户数量统计程序。代码如下:'首先要设置好global.asa&n
- 数据的安全性策略: 数据的生考虑应基于数据的重要性。如果数据不是很重要,那么数据的安全性策略可以稍稍放松一些。然而,如果数据很重要,那么应该
- ndarray的转置(transpose)对于A是由np.ndarray表示的情况:可以直接使用命令A.T。也可以使用命令A.transpo
- 一、什么是模块容器 -> 数据的封装函数 -> 语句的封装类 -> 方法和属性的封装模块 -> 模块就是程序,模块就
- 前言后续还会更新更多优雅的规范。命名风格1. 【强制】代码中的命名均不能以下划线或美元符号开始,也不能以下划线或美元符号结束。&n
- 1、PHP中的抽象类PHP 5 支持抽象类和抽象方法。定义为抽象的类不能被实例化。任何一个类,如果它里面至少有一个方法是被声明为抽象的,那么
- scapy是python写的一个功能强大的交互式数据包处理程序,可用来发送、嗅探、解析和伪造网络数据包,常常被用到网络攻击和测试中。这里就直
- 介绍pandas数据聚合和重组的相关知识,仅供参考。1GroupBy技术1.1简介简介:根据一个或多个键进行分组,每一组应用函数,再进行合并
- 本文实例讲述了JS实现DOM节点插入操作之子节点与兄弟节点插入操作。分享给大家供大家参考,具体如下:<!doctype html>
- 使用torchvision库的datasets类加载常用的数据集或自定义数据集图像识别是计算机视觉中的一个基础任务,它的目标是让计算机能够识
- 1.概述最近项目需要使用程序实现数学微积分,最初想用java实现,后来发现可用文档太少,实现比较麻烦,后来尝试使用python实现,代码量较
- train_comb 为Dataframe数据:train_comb= train_comb.as_matrix() #得到values的n
- 在工作中,我们经常会写出这种代码:import MHeader from '../../components/m-header/m-
- 在使用ionic开发IOS系统微信的时候会有一个苦恼的问题,填写表单的时候键盘会挡住输入框,其实并不算什么大问题,只要用户输入一个字就可以立
- 相信大家在日常的开发中经常会碰到榜单类的活动需求,通常在榜单中都会要求返回排名,今天我们就用MySQL的窗口函数来快速实现一下首先,先建一个
- 优化可能带来的问题优化不总是对一个单纯的环境进行,还很可能是一个复杂的已投产的系统。优化手段本来就有很大的风险,只不过你没能力意识到和预见到
- 计算机键盘每天用得太多了,以致于我们无视它的存在(盲打),当然也很少有人去问这样一个问题——为什么键盘字母的排列方式是QWERTY而不是AB
- 地址:https://youzan.github.io/vant/#/zh-CN/intro一.引入Vant组件库1.首先运行 npm in
- 本文实例讲述了Python使用re模块实现信息筛选的方法。分享给大家供大家参考,具体如下:背景平时工作中,我们经常会处理大量的元数据(Raw
- Dataframe结构放在numpy来看应该是二维矩阵的形式,每一列是一个特征,上面会有个列标题,每一行是一个样本。对Dataframe结构