我正在尝试从 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
=> 商城
www.ouruniversity.department.mit.ac.us
=> mit
www.somestrangeurl.shops.relevantdomain.net
=> relevantdomain
www.example.info
=> 示例
等等..
域的多样性不允许我使用正则表达式,如 how to get domain name from URL 中所示。 (因为我的脚本将在来自真实网络流量的大量 url 上运行,正则表达式必须非常大才能捕获所提到的所有类型的域)。
不幸的是,我的网络研究没有提供任何有效的解决方案。
有没有人知道如何做到这一点?
任何帮助将不胜感激 !
谢谢
最佳答案
使用 tldextract
,它是 urlparse
的更高效版本,tldextract
准确分离 gTLD
或 ccTLD
(通用或国家代码顶级域)来自已注册的 域
和 URL 的 子域
。
>>> import tldextract
>>> ext = tldextract.extract('http://forums.news.cnn.com/')
ExtractResult(subdomain='forums.news', domain='cnn', suffix='com')
>>> ext.domain
'cnn'
关于python - 在 Python 中从 URL 中提取域名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44021846/