首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从URL获取协议+主机名

从URL获取协议+主机名
EN

Stack Overflow用户
提问于 2012-03-09 07:12:38
回答 16查看 186.8K关注 0票数 190

在我的Django应用程序中,我需要从request.META.get('HTTP_REFERER')中的referrer及其协议中获取主机名,以便从URL中获取,例如:

我应该得到:

我查看了其他相关问题,找到了关于urlparse的信息,但这并没有起到作用,因为

>>> urlparse(request.META.get('HTTP_REFERER')).hostname
'docs.google.com'
EN

回答 16

Stack Overflow用户

回答已采纳

发布于 2012-03-09 07:17:43

你应该能够用urlparse (文档:python2python3)做到这一点:

from urllib.parse import urlparse
# from urlparse import urlparse  # Python 2
parsed_uri = urlparse('http://stackoverflow.com/questions/1234567/blah-blah-blah-blah' )
result = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
print(result)

# gives
'http://stackoverflow.com/'
票数 343
EN

Stack Overflow用户

发布于 2012-03-09 09:16:50

https://github.com/john-kurkowski/tldextract

这是urlparse更详细的版本。它会为你检测域和子域。

从他们的文档中:

>>> import tldextract
>>> tldextract.extract('http://forums.news.cnn.com/')
ExtractResult(subdomain='forums.news', domain='cnn', suffix='com')
>>> tldextract.extract('http://forums.bbc.co.uk/') # United Kingdom
ExtractResult(subdomain='forums', domain='bbc', suffix='co.uk')
>>> tldextract.extract('http://www.worldbank.org.kg/') # Kyrgyzstan
ExtractResult(subdomain='www', domain='worldbank', suffix='org.kg')

ExtractResult是一个命名元组,所以很容易访问你想要的部分。

>>> ext = tldextract.extract('http://forums.bbc.co.uk')
>>> ext.domain
'bbc'
>>> '.'.join(ext[:2]) # rejoin subdomain and domain
'forums.bbc'
票数 91
EN

Stack Overflow用户

发布于 2013-12-22 19:20:29

使用urlsplit的Python3

from urllib.parse import urlsplit
url = "http://stackoverflow.com/questions/9626535/get-domain-name-from-url"
base_url = "{0.scheme}://{0.netloc}/".format(urlsplit(url))
print(base_url)
# http://stackoverflow.com/
票数 50
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9626535

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档