在Python中从URL提取域名

2024-09-30 01:36:39 发布

您现在位置: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中所示的正则表达式(因为我的脚本将运行在来自真实网络流量的大量URL上,所以正则表达式必须非常庞大才能捕获所提到的所有类型的域)。
不幸的是,我的网络研究没有提供任何有效的解决方案。
有人知道怎么做吗?
任何帮助都将不胜感激
多谢各位


Tags: thenamefromhttpscomurl列表domain
3条回答

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

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

通过正则表达式的简单解决方案

import re

def domain_name(url):
    return url.split("www.")[-1].split("//")[-1].split(".")[0]

使用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'

相关问题 更多 >

    热门问题