获取链接的根域

Gav*_*ulz 18 python regex dns root

我有一个链接,如http://www.techcrunch.com/,我想获得链接的techcrunch.com部分.我如何在python中解决这个问题?

Ben*_*ank 25

使用urlparse获取主机名很简单:

hostname = urlparse.urlparse("http://www.techcrunch.com/").hostname
Run Code Online (Sandbox Code Playgroud)

然而,获得"根域"会更成问题,因为它没有在语法意义上定义.什么是"www.theregister.co.uk"的根域?网络使用默认域名怎么样?"devbox12"可以是有效的主机名.

处理此问题的一种方法是使用公共后缀列表,该列表尝试编目真正的顶级域名(例如".com",".net",".org")以及像TLD一样使用的私有域名. (例如".co.uk"或甚至".github.io").您可以使用publicsuffix2库从Python访问PSL :

import publicsuffix
import urlparse

def get_base_domain(url):
    # This causes an HTTP request; if your script is running more than,
    # say, once a day, you'd want to cache it yourself.  Make sure you
    # update frequently, though!
    psl = publicsuffix.fetch()

    hostname = urlparse.urlparse(url).hostname

    return publicsuffix.get_public_suffix(hostname, psl)
Run Code Online (Sandbox Code Playgroud)


Moh*_*sin 8

URL的一般结构:

方案:// netloc /路径;参数查询#片段

作为TIMTOWTDI的座右铭:

使用urlparse,

>>> from urllib.parse import urlparse  # python 3.x
>>> parsed_uri = urlparse('http://www.stackoverflow.com/questions/41899120/whatever')  # returns six components
>>> domain = '{uri.netloc}/'.format(uri=parsed_uri)
>>> result = domain.replace('www.', '')  # as per your case
>>> print(result)
'stackoverflow.com/'  
Run Code Online (Sandbox Code Playgroud)

使用tldextract,

>>> import tldextract  # The module looks up TLDs in the Public Suffix List, mantained by Mozilla volunteers
>>> tldextract.extract('http://forums.news.cnn.com/')
ExtractResult(subdomain='forums.news', domain='cnn', suffix='com')
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

>>> extracted = tldextract.extract('http://www.techcrunch.com/')
>>> '{}.{}'.format(extracted.domain, extracted.suffix)
'techcrunch.com'
Run Code Online (Sandbox Code Playgroud)

tldextract另一方面,根据公共后缀列表查找当前生存的gTLD,通用顶级域名(通用顶级域名)和国家和地区代码顶级域名(国家地区代码顶级域名)是什么样的.因此,给定一个URL,它从其域中知道其子域,并从其国家代码中知道其域.

Cheerio!:)