Python获取TLD

2024-09-28 22:29:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我的函数有问题,应该从域中删除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

有人能帮我解决这个问题吗


Tags: 子域函数代码comtruegetobjectexample
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中。然后你只需要用{}点{}

通过一个非常简单的字符串操作,这就是您想要的吗

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

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

你可以使用过滤。看起来get_tld工作正常,但join不正确

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

相关问题 更多 >