python如何基于redis實(shí)現(xiàn)ip代理池
這篇文章主要介紹了python如何基于redis實(shí)現(xiàn)ip代理池,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
使用apscheduler庫(kù)定時(shí)爬取ip,定時(shí)檢測(cè)ip刪除ip,做了2層檢測(cè),第一層爬取后放入redis——db0進(jìn)行檢測(cè),成功的放入redis——db1再次進(jìn)行檢測(cè),確保獲取的代理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數(shù)據(jù)庫(kù)里的ip def remove_ip(ip,redis_conn): redis_conn.zrem("IP", ip) print("已刪除 %s..." % ip) # 獲取redis數(shù)據(jù)庫(kù)里一共有多少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和端口到數(shù)據(jù)庫(kù)里 def add_ip(ip, port,redis_conn): # nx: 不要更新已有的元素??偸翘砑有碌脑?只有True,F(xiàn)alse 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 # 隨機(jī)獲取一個(gè)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錯(cuò)誤失效就刪除 remove_ip(ip,redis_conn) scheduler = BlockingScheduler() scheduler.add_job(func=aps_detection_ip, args=('檢測(cè)循環(huán)任務(wù)0',redis_conn_0), trigger='interval', seconds=3, id='aps_detection_ip_task0',max_instances=10) scheduler.add_job(func=spider_ip, args=('獲取循環(huán)任務(wù)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=('檢測(cè)循環(huán)任務(wù)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("獲取循環(huán)任務(wù)") scheduler.start() # aps_detection_ip("檢測(cè)循環(huán)任務(wù)")
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python模塊相關(guān)知識(shí)點(diǎn)小結(jié)
這篇文章主要介紹了Python模塊相關(guān)知識(shí)點(diǎn),總結(jié)分析了Python模塊的功能、原理、使用方法與操作注意事項(xiàng),需要的朋友可以參考下2020-03-03從Python的源碼來解析Python下的freeblock
這篇文章主要介紹了從Python的源碼來解析Python下的freeblock,包括內(nèi)存空間分配等知識(shí),需要的朋友可以參考下2015-05-05詳解selenium + chromedriver 被反爬的解決方法
這篇文章主要介紹了詳解selenium + chromedriver 被反爬的解決方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10Python實(shí)現(xiàn)連接兩個(gè)無(wú)規(guī)則列表后刪除重復(fù)元素并升序排序的方法
這篇文章主要介紹了Python實(shí)現(xiàn)連接兩個(gè)無(wú)規(guī)則列表后刪除重復(fù)元素并升序排序的方法,涉及Python針對(duì)列表的合并、遍歷、判斷、追加、排序等操作技巧,需要的朋友可以參考下2018-02-02使用python讀寫txt和json(jsonl)大文件的方法步驟
在Python中讀取txt和json(jsonl)大文件并保存到字典是一項(xiàng)非常常見的操作,這篇文章主要給大家介紹了關(guān)于使用python讀寫txt和json(jsonl)大文件的方法步驟,需要的朋友可以參考下2023-12-12Python機(jī)器學(xué)習(xí)應(yīng)用之支持向量機(jī)的分類預(yù)測(cè)篇
最近完成的一個(gè)項(xiàng)目用到了SVM,之前也一直有聽說支持向量機(jī),知道它是機(jī)器學(xué)習(xí)中一種非常厲害的算法。利用將近一個(gè)星期的時(shí)間學(xué)習(xí)了一下支持向量機(jī),把原理推了一遍,感覺支持向量機(jī)確實(shí)挺厲害的,這篇文章帶你了解它2022-01-01