我在应该从域中删除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
有人能帮我解决这个问题吗?
发布于 2021-04-26 18:01:35
通过一个非常简单的字符串操作,这就是你想要的吗?
d1 = 'asdf.xyz.example.com'
output = '.'.join(d1.split('.')[:-1])
# output = 'asdf.xyz.example'
d2 = 'example.com'
output = '.'.join(d2.split('.')[:-1])
# output = 'example'发布于 2021-04-26 18:03:41
您可以使用过滤。看起来get_tld像预期的那样工作,但是join不正确
domain = '.'.join(filter(lambda x: len(x), [res.subdomain, res.domain]))发布于 2021-04-26 18:05:01
另一个简单的版本是:
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(base) join tĥ就行了。
https://stackoverflow.com/questions/67264512
复制相似问题