如何在Python中获取域名信息?代码实现示例

2021年11月16日18:39:56 发表评论 1,294 次浏览

如何在Python中获取域名信息?了解如何使用 WHOIS 验证域名,以及如何使用 Python 获取域名信息,例如域名注册商、创建日期、到期日期等。

域名是标识网络域的字符串,它代表 IP 资源,例如托管网站的服务器或可以访问 Internet 的计算机。

简单来说,我们所知道的域名就是人们在浏览器 URL 中输入要访问的网站地址。

Python如何获取域名信息?在本教程中,我们将使用Python 中的whois库来验证域名并检索各种域信息,例如创建和到期日期、域注册商、所有者的地址和国家/地区等。

首先,让我们安装库:

pip3 install python-whois

WHOIS是一种查询和响应协议,常用于查询存储注册域名的数据库。它以人类可读的格式存储和交付内容。whois库只是直接查询 WHOIS 服务器,而不是通过中间 Web 服务。

在 Linux 中还有一个简单的whois 命令来提取域信息,但由于我们是 Python 开发人员,所以我们将使用 Python 来实现这一点。

Python获取域名信息示例:验证域名

如何在Python中获取域名信息?在本节中,我们将使用whois来判断域名是否存在并已注册,以下函数执行此操作:

import whois # pip install python-whois

def is_registered(domain_name):
    """
    A function that returns a boolean indicating 
    whether a `domain_name` is registered
    """
    try:
        w = whois.whois(domain_name)
    except Exception:
        return False
    else:
        return bool(w.domain_name)

Python如何获取域名信息whois.whois()函数为不存在的域引发异常,并且即使域未注册也可能返回而不会引发任何异常,这就是我们检查是否domain_name存在的原因,让我们测试这个函数:

# list of registered & non registered domains to test our function
domains = [
    "thepythoncode.com",
    "google.com",
    "github.com",
    "unknownrandomdomain.com",
    "notregistered.co"
]
# iterate over domains
for domain in domains:
    print(domain, "is registered" if is_registered(domain) else "is not registered")

我们已经定义了一些已知域和其他不存在的域,这是输出:

thepythoncode.com is registered
google.com is registered
github.com is registered
unknownrandomdomain.com is not registered
notregistered.co is not registered

太棒了,在下一节中,我们将看到如何获取有关域名的各种有用信息。

获取域 WHOIS 信息

Python如何获取域名信息?使用这个库非常简单,我们只需将域名传递给whois.whois()函数:

import whois

# test with Google domain name
domain_name = "google.com"
if is_registered(domain_name):
    whois_info = whois.whois(domain_name)

现在要获取域名注册商(管理域名预留的公司),我们只需访问属性注册商:

    # print the registrar
    print("Domain registrar:", whois_info.registrar)

获取 WHOIS 服务器:

    # print the WHOIS server
    print("WHOIS server:", whois_info.whois_server)

Python获取域名信息示例 - 域创建和到期日期:

    # get the creation time
    print("Domain creation date:", whois_info.creation_date)
    # get expiration date
    print("Expiration date:", whois_info.expiration_date)

输出:

Domain registrar: MarkMonitor Inc.
WHOIS server: whois.markmonitor.com        
Domain creation date: 1997-09-15 04:00:00  
Expiration date: 2028-09-14 04:00:00 

如何在Python中获取域名信息?要查看其他各种 WHOIS 信息,例如名称服务器、国家/地区、城市、州、地址等,只需打印whois_info

    # print all other info
    print(whois_info)

结论

你有它!你刚刚学习了在 Python 中获取域名信息的最简单快捷的方法。检查python-whois Github 存储库

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: