从url Python中提取域名

2024-05-21 08:21:53 发布

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

我正在尝试从url列表中提取域名。就像在 https://stackoverflow.com/questions/18331948/extract-domain-name-from-the-url
我的问题是url可以是关于所有内容的,很少有示例:
m.google.com=>;google
m.docs.google.com=>;google
www.someisotericdomain.innersite.mall.co.uk=>;mall
www.ouruniversity.department.mit.ac.us=>;mit
www.somestrangeurl.shops.relevantdomain.net=>;relevantdomain
www.example.info=>;example
等等….
域的多样性不允许我使用如how to get domain name from URL所示的regex(因为我的脚本将在实时网络流量上运行,所以regex必须非常庞大才能捕获所提到的所有类型的域)。
不幸的是,我的网络研究没有提供任何有效的解决方案。
有人知道怎么做吗?
任何帮助都将不胜感激!
谢谢你


Tags: namefromgtcomurl列表mitexample
3条回答

使用tldextract这是urlparse的更有效版本,tldextract准确地将gTLDccTLD(通用或国家代码顶级域)与URL的注册domainsubdomains分开。

>>> import tldextract
>>> ext = tldextract.extract('http://forums.news.cnn.com/')
ExtractResult(subdomain='forums.news', domain='cnn', suffix='com')
>>> ext.domain
'cnn'

使用regex,您可以使用以下方法:

(?<=\.)([^.]+)(?:\.(?:co\.uk|ac\.us|[^.]+(?:$|\n)))

https://regex101.com/r/WQXFy6/5

注意,您必须注意特殊情况,例如co.uk

似乎可以对该url使用urlparsehttps://docs.python.org/3/library/urllib.parse.html,然后提取netloc。

从netloc中,您可以使用split轻松地提取域名

相关问题 更多 >