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

Ip address checker doesn't output IP address

根据 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版本是idle 3.8.

原来你的正则表达式哪里错了: 我更新了代码并使用 requests get:

findall 将 return 一个元素列表,因为你只得到一个 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])