在Python中使用get_tld()函数生成随机的TLD( 域名)-20个例子
发布时间:2023-12-29 09:51:28
在Python中使用get_tld()函数生成随机的TLD( 域名)可以通过安装和导入tldextract库来实现。get_tld()函数可以解析给定URL的域名,并返回其 域名。
下面是20个使用get_tld()函数生成随机TLD的示例:
1. 导入tldextract库和random库:
import tldextract import random
2. 创建一个包含常见TLD的列表:
tlds = ['com', 'net', 'org', 'edu', 'gov', 'mil', 'int', 'eu', 'au', 'uk', 'fr', 'it', 'jp', 'cn', 'us', 'de', 'ca', 'ru', 'br', 'in']
3. 随机选取一个TLD:
random_tld = random.choice(tlds)
4. 使用get_tld()函数生成随机的 域名:
random_domain = get_tld(netloc='example.com', as_object=True, fail_silently=True).registered_domain
random_url = f'https://www.{random_domain}'
5. 完整代码示例:
import tldextract
import random
tlds = ['com', 'net', 'org', 'edu', 'gov', 'mil', 'int', 'eu', 'au', 'uk', 'fr', 'it', 'jp', 'cn', 'us', 'de', 'ca', 'ru', 'br', 'in']
random_tld = random.choice(tlds)
random_domain = get_tld(netloc='example.com', as_object=True, fail_silently=True).registered_domain
random_url = f'https://www.{random_domain}'
print(random_url)
这个例子将生成一个随机的URL,类似于https://www.example.com,其中example.com中的.com是从预定义的TLD列表中随机选择的。你可以根据需要修改TLD列表,并使用get_tld()函数生成自定义的随机URL。
