Python 正则匹配网页内的IP地址及端口号
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # @Date : 2017-08-30 20:38:23
4 # @Author : EnderZhou (zptxwd@gmail.com)
5 # @Link : http://www.cnblogs.com/enderzhou/
6 # @Version : $Id$
7
8 import requests
9 import re
10
11 def open_url(url):
12 req = requests.get(url=url,headers=headers)
13 html = req.content
14 return html
15
16
17 def get_ipandport(html):
18 #默认网页内的IP地址位于端口号之前,并且中间至少隔了一个非数字的字符串
19 # (?:((?:\d|[1-9]\d|1\d{2}|2[0-5][0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-5][0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-5][0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-5][0-5])) 用于匹配IP地址
20 # (6[0-5]{2}[0-3][0-5]|[1-5]\d{4}|[1-9]\d{1,3}|[0-9]) 用于匹配端口号 注意端口号匹配规则应从大到校排序
21 # 使用 ([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5]) 替换即可观察到原因。
22 # 使用\D+?匹配IP地址与端口号中间至少隔了一个非数字的字符串
23 p = r'(?:((?:\d|[1-9]\d|1\d{2}|2[0-5][0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-5][0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-5][0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-5][0-5]))\D+?(6[0-5]{2}[0-3][0-5]|[1-5]\d{4}|[1-9]\d{1,3}|[0-9]))'
24 iplist = re.findall(p,html)
25 for each in iplist:
26 print(each)
27
28 if __name__ == '__main__':
29 url = 'http://www.66ip.cn/'
30 headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36'}
31 get_ipandport(open_url(url))
本文所编写的使用正则对IP地址及端口爬取函数后续将与之前的网页代理服务器验证代码函数整合使用