这是Get protocol + host name from URL的扩展,添加了这样的要求:我只想要域名,而不是子域。
所以,比如说,
Input: classes.usc.edu/xxx/yy/zz
Output: usc.edu
Input: mail.google.com
Output: google.com
Input: google.co.uk
Output: google.co.uk对于更多的上下文,我接受来自用户的一个或多个种子URL,然后在链接上运行一个刮伤爬虫。我需要域名(没有子域)来设置allowed_urls属性。
我也看过Python urlparse -- extract domain name without subdomain,但答案似乎过时了。
我当前的代码使用urlparse,但这也得到了我不想要的子域.
from urllib.parse import urlparse
uri = urlparse('https://classes.usc.edu/term-20191/classes/csci/')
f'{uri.scheme}://{uri.netloc}/'
# 'https://classes.usc.edu/'有没有一种(希望是stdlib)获得python-3.x中的域的方法?
发布于 2019-04-20 01:10:50
在进行域解析时,我使用的是tldextract。
在您的情况下,您只需要组合domain + suffix
import tldextract
tldextract.extract('mail.google.com')
Out[756]: ExtractResult(subdomain='mail', domain='google', suffix='com')
tldextract.extract('classes.usc.edu/xxx/yy/zz')
Out[757]: ExtractResult(subdomain='classes', domain='usc', suffix='edu')
tldextract.extract('google.co.uk')
Out[758]: ExtractResult(subdomain='', domain='google', suffix='co.uk')https://stackoverflow.com/questions/55769341
复制相似问题