IP及端口号的获取及保存【实用】

import urllib.request
import re
import os
def url_open(url):
    res=urllib.request.Request(url)
    res.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; rv:51.0) Gecko/20100101 Firefox/51.0')
    req=urllib.request.urlopen(res)
    html=req.read()
    return  html

def ip(url,file,count,user_input):
    try:
        html=url_open(url).decode('utf-8')
    except UnicodeDecodeError:
        html=url_open(url)
    s=r'(\d+\.\d+\.\d+\.\d+)'
    d=r'"PORT">(\d*)</td>'
    ips=re.findall(s,html)           #获取IP
    dk=re.findall(d,html)            #获取端口号
    dictionary = dict(zip(ips, dk))  #将IP 和端口号压缩成字典
    ips = list(dictionary)           #获取IP字典的Key值
    for ip in ips:                  #通过遍历Key,取出对应的Value
        with open(file, 'a+') as f:
            f.write(ip+'  ')        #保存IP
            f.write(dictionary[ip]+'\n')#保存端口号
            print('第%s条'%count)
            count+=1
        if count==user_input+1: #用户所需条数控制器
            print('获取完成,请到%s文件夹下查看!'%file)
            break
    return count
if __name__ =='__main__':
    user_input=int(input('要下载多少条:'))
    file='D:\My Documents\Desktop\\ips.txt'
    if os.path.exists(file):
        pass
    i=1   #页面循环控制器
    count = 1 #IP计数器
    while i:
        try:
            url = 'http://www.kuaidaili.com/free/inha/%s/'%i
            count = ip(url,file,count,user_input)
            if count == user_input+1:
                break
            i+=1
        except TypeError: #无法解码C++转义字符,跳过当前页
            i+=1
            continue
        except urllib.error.HTTPError: #获取网页地址不稳定,时常503
            continue
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值