python如何基于redis实现ip代理池
作者:Maple_feng 时间:2022-11-05 20:49:08
这篇文章主要介绍了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
标签:python,redis,ip,代理
0
投稿
猜你喜欢
Python 实现两个服务器之间文件的上传方法
2022-04-22 10:32:03
你是真正的用户体验设计者吗? Ⅵ
2008-04-19 18:23:00
vue项目中将element-ui table表格写成组件的实现代码
2024-05-28 15:55:31
关于使用PLSQL Developer时出现报错ora-12514的问题
2024-01-15 09:12:17
Python Numpy 自然数填充数组的实现
2023-12-18 16:51:37
python实现线程池的方法
2023-03-10 14:08:06
JS中判断null、undefined与NaN的方法
2024-04-19 09:54:27
Python安装spark的详细过程
2021-05-17 09:59:05
javascript中直接写php代码的方法
2024-05-02 16:27:46
一篇文章带你了解python标准库--datetime模块
2022-08-21 03:42:04
python 的列表遍历删除实现代码
2023-07-15 11:44:35
ASP.NET MVC4入门教程(五):从控制器访问数据模型
2024-06-05 09:25:42
Go语言获取数组长度的方法
2024-04-30 10:01:19
Python+pytorch实现天气识别
2021-09-23 18:49:13
python3中类的继承以及self和super的区别详解
2023-02-23 20:31:25
Python 虚拟环境迁移到其他电脑的实现
2023-04-16 19:08:13
ASP.NET程序中用Repeater实现分页
2024-05-09 09:02:48
Mysql日期和时间函数大全
2011-03-08 09:52:00
PYQT5实现控制台显示功能的方法
2023-08-08 11:11:53
Python真题案例之最长回文子串 周期串详解
2021-12-01 02:57:02