IP 地址检查器不输出 IP 地址



按照这里的代码,我得到了一个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地址不是我的,来自这里

实际输出:

we will try to open this url, in order to get IP Address
http://checkip.dyndns.org
your IP Address is:  []

我刚刚从网站上复制,然后修复了错误。我做错了什么。请帮忙...

我的 python 版本是空闲的 3.8。

事实证明,您的正则表达式出错了: 我已经更新了代码并使用请求得到:

findall将返回一个元素列表,因为您只得到一个ip,只需使用[0]

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])

最新更新