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并判斷是否可用和定時更新的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python解析庫Beautiful?Soup安裝的詳細步驟
Beautiful?Soup是python的一個庫,最主要的功能是從網(wǎng)頁抓取數(shù)據(jù),下面這篇文章主要給大家介紹了關(guān)于python解析庫Beautiful?Soup安裝的詳細步驟,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2023-04-04
詳解Python中的__getitem__方法與slice對象的切片操作
Python中想要使類的實例像list一樣使用下標,可以用__getitem__方法,而配合slice對象則可以實現(xiàn)list一樣的切片,詳解Python中的__getitem__方法與slice對象的切片操作2016-06-06
python字符串分割常用方法(str.split()和正則)
在Python中字符串是一種非常常見的數(shù)據(jù)類型,在實際應(yīng)用中我們經(jīng)常需要對字符串進行分割,以便對其中的內(nèi)容進行處理,這篇文章主要給大家介紹了關(guān)于python字符串分割(str.split()和正則)的相關(guān)資料,需要的朋友可以參考下2023-11-11
Python2.7版os.path.isdir中文路徑返回false的解決方法
這篇文章主要為大家詳細介紹了Python2.7版os.path.isdir中文路徑返回false的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-06-06
對python條件表達式的四種實現(xiàn)方法小結(jié)
今天小編就為大家分享一篇對python條件表達式的四種實現(xiàn)方法小結(jié),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01

