Python采集代理ip并判斷是否可用和定時更新的方法
更新時間:2018年05月07日 11:05:16 作者:lilongsy
今天小編就為大家分享一篇Python采集代理ip并判斷是否可用和定時更新的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
網(wǎng)上有很多免費的ip地址,都是可以使用的,但是如果手動來獲取太麻煩,這里通過Python自動抓取,可以批量獲取。
代碼如下:
# -*- coding: utf-8 -*- import re import urllib2 import json import os import time import socket class ProxyIp(object): def __init__(self): self.path = os.path.split(os.path.realpath(__file__))[0] # Get latest proxy ip and download to json def update_ip(self): print 'Update Ip' url = 'http://www.ip3366.net/free/' req = urllib2.Request(url) response = urllib2.urlopen(req) matches = re.findall( ur'(\d+.\d+.\d+.\d+)</td>\s+<td>(\d+)</td>\s+<td>.*?</td>\s+<td>(HTTPS?)</td>', response.read(), re.I ) ls = [] for match in matches: if self.is_open(match[0], match[1]): ls.append({'ip':match[0], 'port':match[1], 'protocol': match[2]}) with open('%s/ip.json' % self.path, 'w') as f: json.dump(ls, f) return ls # whether the ips is last or old. def is_last(self): m_time = int(os.path.getmtime('%s/ip.json' % self.path)) now_time = int(time.time()) return (now_time - m_time) > 60*60*4 # 4 hours @staticmethod def is_open(ip, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect(ip, int(port)) return True except: print 'Faild IP: %s:%s' % (ip, port) return False def get_proxy_ips(self): if not self.is_last(): return self.update_ip() else: with open('%s/ip.json' % self.path, 'r') as f: return json.load(f)
以上這篇Python采集代理ip并判斷是否可用和定時更新的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python 中pandas索引切片讀取數(shù)據(jù)缺失數(shù)據(jù)處理問題
pandas是一個Python軟件包,提供快速,靈活和富于表現(xiàn)力的數(shù)據(jù)結構,旨在使使用“關系”或“標記”數(shù)據(jù)既簡單又直觀。這篇文章主要介紹了pandas索引切片讀取數(shù)據(jù)缺失數(shù)據(jù)處理,需要的朋友可以參考下2019-10-10python中string模塊各屬性以及函數(shù)的用法介紹
下面小編就為大家?guī)硪黄猵ython中string模塊各屬性以及函數(shù)的用法介紹。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-05-05使用tf.keras.MaxPooling1D出現(xiàn)錯誤問題及解決
這篇文章主要介紹了使用tf.keras.MaxPooling1D出現(xiàn)錯誤問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12Python中使用封裝類還是函數(shù)以及它們的區(qū)別
在Python編程中,類和函數(shù)都是重要的代碼組織工具,但它們在封裝性、狀態(tài)保持、可重用性、繼承與多態(tài)、設計模式、代碼組織、執(zhí)行流程、參數(shù)傳遞、返回值和上下文管理等方面存在明顯區(qū)別2024-10-10