【问题标题】:Python - get TLDPython - 获取顶级域名
【发布时间】:2021-04-26 09:57:29
【问题描述】:

我的函数有问题,应该从域中删除 tld。如果域有一些子域,它可以正常工作。例如:

输入:asdf.xyz.example.com

输出:asdf.xyz.example

问题是当域没有任何子域时,域前面有一个点

输入:example.com

输出:.example

这是我的代码:

 res = get_tld(domain, as_object=True, fail_silently=True, fix_protocol=True)
 domain = '.'.join([res.subdomain, res.domain])

函数get_tld来自tld library

有人可以帮我解决这个问题吗?

【问题讨论】:

  • get_tld 的实现是什么?
  • 对不起,我忘记提了。我正在使用 tld 库pypi.org/project/tld

标签: python tld


【解决方案1】:

通过非常简单的字符串操作,这就是您要找的吗?

d1 = 'asdf.xyz.example.com'
output = '.'.join(d1.split('.')[:-1])
# output = 'asdf.xyz.example'

d2 = 'example.com'
output = '.'.join(d2.split('.')[:-1])
# output = 'example'

【讨论】:

    【解决方案2】:

    您可以使用过滤。看起来get_tld 按预期工作,但join 不正确

    domain = '.'.join(filter(lambda x: len(x), [res.subdomain, res.domain]))
    

    【讨论】:

      【解决方案3】:

      另一个简单的版本是这样的:

      def remove_tld(url):
          *base, tld = url.split(".")
          return ".".join(base)
      
      
      url = "asdf.xyz.example.com"
      print(remove_tld(url))    # asdf.xyz.example
      
      url = "example.com"
      print(remove_tld(url))    # example
      

      *base, tld = url.split(".") 将 TLD 放入 tld 并将其他所有内容放入 base。那么你只需join tĥat 和".".join(base)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-18
        • 2021-10-31
        • 2018-12-30
        • 1970-01-01
        • 2021-11-23
        • 1970-01-01
        • 2011-03-28
        • 1970-01-01
        相关资源
        最近更新 更多