IP及端口号的获取及保存【实用】
2017-11-03 10:45
197 查看
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
相关文章推荐
- nginx模块编程之获取客户ip及端口号
- JavaWeb 获取请求网络协议、IP、端口号、项目根路径
- 获取用户的ip,端口号,服务端地址,访问端口号
- js 获取请求网络协议、IP、端口号、项目名称
- [导入]【原】C#里获取客户端IP,端口号的简单示例
- jsp 获取服务器ip 以及端口号
- 获取远程文件保存为本地文件(精简实用)
- 获取请求ip与端口号
- JSP中的几个实用函数(时间判断/IP获取/累计次数/视频播放等)
- [导入]【原】C#里获取客户端IP,端口号的简单示例
- 获取本地IP和端口号的指令
- C#里获取客户端IP,端口号的简单示例
- java实现从RUI获取文件并保存本地(实用方法)
- 根据客户端套接字获取客户机的IP和端口号,其形式为IP:port
- 记家庭建站的一些事,实现获取动态Ip、模拟登陆万网、修改保存域名解析
- java获取本机IP,系统随机分配端口号,获取当前线程ID
- C#获取本地计算机名,IP,MAC地址,硬盘ID
- sessionStorage的保存和获取
- java保存获取Web内容的文件
- 网页获取客户端IP的两种方法