【问题标题】:How to distinguish a domain and a hostname in python如何在python中区分域和主机名
【发布时间】:2017-06-09 14:21:03
【问题描述】:

域类似于:google.com、yahoo.com。它也有一个whois记录

主机名类似于:m.google.com、www.google.com、images.google.com

域可以有非常有趣的 TLD 和 ccTLD:google.co.uk、google.academy、google.xxx

主机名也可以是这样的:ma​​il.services.1.google.com, xxx.google.com

问题是:我有一个字符串变量,我想确定该值是主机名还是域。在python中有没有聪明的方法来区分它们?

【问题讨论】:

    标签: python hostname urlparse


    【解决方案1】:

    您似乎已经知道如何区分它们了。

    使用urllib.parse分解字符串,然后编写自己的逻辑来决定。

    文档:https://docs.python.org/3/library/urllib.parse.html

    【讨论】:

    • 此外,您可以使用 TLD 列表 @iana.org/domains/root/db 来区分解析后的域和主机名。
    • urllib.parse 只给我们主机名,而不是域。我尝试过这个。您编写的 TLD 列表仅包含 TLD 而不是 ccTLD!这里的关键问题是ccTLD。否则你不包括按点分割后的最后一部分
    【解决方案2】:

    我找到了答案。我们可以使用 tldextract 包来做到这一点。

    from tldextract import tldextract
    
    test_str = 'mail.google.co.uk'
    te_result = tldextract.extract(test_str)
    domain = '{}.{}'.format(te_result.domain, te_result.suffix)
    print('domain: {}'.format(domain))
    print('is_hostname: {}'.format(test_str != domain))
    print('is_domain: {}'.format(test_str == domain))
    

    答案:

    domain: google.co.uk
    is_hostname: True
    is_domain: False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-20
      • 2015-09-27
      • 1970-01-01
      • 2010-10-05
      • 2011-05-27
      • 2011-05-19
      • 2019-05-13
      • 2012-09-28
      相关资源
      最近更新 更多