Python采集代理ip并判斷是否可用和定時(shí)更新的方法
網(wǎng)上有很多免費(fèi)的ip地址,都是可以使用的,但是如果手動(dòng)來(lái)獲取太麻煩,這里通過(guò)Python自動(dòng)抓取,可以批量獲取。
代碼如下:
# -*- 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并判斷是否可用和定時(shí)更新的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python 中pandas索引切片讀取數(shù)據(jù)缺失數(shù)據(jù)處理問(wèn)題
pandas是一個(gè)Python軟件包,提供快速,靈活和富于表現(xiàn)力的數(shù)據(jù)結(jié)構(gòu),旨在使使用“關(guān)系”或“標(biāo)記”數(shù)據(jù)既簡(jiǎn)單又直觀。這篇文章主要介紹了pandas索引切片讀取數(shù)據(jù)缺失數(shù)據(jù)處理,需要的朋友可以參考下2019-10-10python中string模塊各屬性以及函數(shù)的用法介紹
下面小編就為大家?guī)?lái)一篇python中string模塊各屬性以及函數(shù)的用法介紹。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-05-05使用tf.keras.MaxPooling1D出現(xiàn)錯(cuò)誤問(wèn)題及解決
這篇文章主要介紹了使用tf.keras.MaxPooling1D出現(xiàn)錯(cuò)誤問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12Python中使用封裝類還是函數(shù)以及它們的區(qū)別
在Python編程中,類和函數(shù)都是重要的代碼組織工具,但它們?cè)诜庋b性、狀態(tài)保持、可重用性、繼承與多態(tài)、設(shè)計(jì)模式、代碼組織、執(zhí)行流程、參數(shù)傳遞、返回值和上下文管理等方面存在明顯區(qū)別2024-10-10基于windows下pip安裝python模塊時(shí)報(bào)錯(cuò)總結(jié)
今天小編就為大家分享一篇基于windows下pip安裝python模塊時(shí)報(bào)錯(cuò)總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06python里glob模塊知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家整理的是一篇關(guān)于python里glob模塊知識(shí)點(diǎn)總結(jié),有需要的朋友們可以參考下。2021-01-01