按照来自here的代码,我有一个IP地址检查器。但是,不是输出IP地址,而是输出[]
。代码:
import urllib.request
import re
print("we will try to open this url, in order to get IP Address")
url = "http://checkip.dyndns.org"
print(url)
request = urllib.request.urlopen(url).read()
theIP = re.findall(r"d{1,3}.d{1,3}.d{1,3}.d{1,3}", request.decode('utf-8'))
print("your IP Address is: ", theIP)
预期输出:
we will try to open this url, in order to get IP Address
http://checkip.dyndns.org
your IP Address is: 40.74.89.185
那里的IP地址不是我的,它来自HERE 。
实际输出:
we will try to open this url, in order to get IP Address
http://checkip.dyndns.org
your IP Address is: []
我刚刚从网站上复制了内容,然后更正了错误。我做错了什么。请帮助...
我的python版本空闲3.8。
答案 0 :(得分:1)
证明您的正则表达式出现错误: 我已经更新了代码,并使用了请求get:
findall
将返回元素列表,因为仅使用[0]即可获得一个IP返回值。
from requests import get
import re
iphtml = get('http://checkip.dyndns.org').text
theIP = re.findall( r'[0-9]+(?:\.[0-9]+){3}', iphtml)
print(f"Your IP is: {theIP[0]}")
您的代码已更新:
import urllib.request
import re
print("we will try to open this url, in order to get IP Address")
url = "http://checkip.dyndns.org"
print(url)
request = urllib.request.urlopen(url).read()
theIP = re.findall(r'[0-9]+(?:\.[0-9]+){3}', request.decode('utf-8'))
print("your IP Address is: ", theIP[0])