python获取外网地址
1 # coding=gbk 2 import sys,urllib.request,re 3 4 url = "http://www.3322.org/dyndns/getip" #网页地址 5 myPage=urllib.request.urlopen(url).read() 6 myPage = myPage.decode('GBK') 7 match = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}') 8 line = match.findall(myPage) 9 print (line[0])
第一行不加可能报错 SyntaxError: Non-UTF-8 code starting with '\xcd' in file learn.py on line 4, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
4-5两行通过3322.org取到自己的IP地址
第6行不加直接print (myPage)可以看到IP,但是内容为b'xxx.xxx.xxx.xxx\n'
7-8行正则匹配获取到IP,否则内容是b'xxx.xxx.xxx.xxx\n'
第9行输出第一个匹配的(一共就一个)