usr*_*371 5 python regex url packages server
我想从网址列表中提取域名.就像从网址中提取域名一样
我的问题是网址可以是关于所有内容的,很少有例子:
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
依此类推.
域名的多样性不允许我使用正则表达式,如如何从URL获取域名(因为我的脚本将在实时网络流量上运行,正则表达式必须是巨大的,以便捕获所提到的各种域).
不幸的是我的网络研究没有提供任何有效的解决方案.
有没有人知道如何做到这一点?
任何帮助将不胜感激 !
谢谢
aka*_*iya 12
使用tldextract更有效的版本urlparse, tldextract准确地将gTLDor ccTLD(通用或国家代码顶级域)与注册domain和subdomainsURL 分开.
>>> import tldextract
>>> ext = tldextract.extract('http://forums.news.cnn.com/')
ExtractResult(subdomain='forums.news', domain='cnn', suffix='com')
>>> ext.domain
'cnn'
Run Code Online (Sandbox Code Playgroud)
小智 5
看来你可以使用 urlparse https://docs.python.org/3/library/urllib.parse.html来获取该 url,然后提取 netloc。
从 netloc 中,您可以使用 split 轻松提取域名