从 URL 获取协议+主机名
- 2025-03-04 08:27:00
- admin 原创
- 75
问题描述:
在我的 Django 应用中,我需要从引荐来源获取主机名request.META.get('HTTP_REFERER')
及其协议,以便从类似以下的 URL 中获取:
https://docs.google.com/spreadsheet/ccc?key=blah-blah-blah-blah#gid=1
https://stackoverflow.com/questions/1234567/blah-blah-blah-blah
http://www.example.com
https://www.other-domain.example/whatever/blah/blah/?v1=0&v2=blah+blah
我应该得到:
https://docs.google.com/
https://stackoverflow.com/
http://www.example.com
https://www.other-domain.example/
我查看了其他相关问题,发现了有关 urlparse 的信息,但这并没有起到作用,因为
>>> urlparse(request.META.get('HTTP_REFERER')).hostname
'docs.google.com'
解决方案 1:
您应该能够使用urlparse
(文档:python2,python3)来完成此操作:
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/'
解决方案 2:
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'
解决方案 3:
Python3 使用urlsplit:
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/
解决方案 4:
>>> import urlparse
>>> url = 'http://stackoverflow.com/questions/1234567/blah-blah-blah-blah'
>>> urlparse.urljoin(url, '/')
'http://stackoverflow.com/'
解决方案 5:
纯字符串操作:):
>>> url = "http://stackoverflow.com/questions/9626535/get-domain-name-from-url"
>>> url.split("//")[-1].split("/")[0].split('?')[0]
'stackoverflow.com'
>>> url = "stackoverflow.com/questions/9626535/get-domain-name-from-url"
>>> url.split("//")[-1].split("/")[0].split('?')[0]
'stackoverflow.com'
>>> url = "http://foo.bar?haha/whatever"
>>> url.split("//")[-1].split("/")[0].split('?')[0]
'foo.bar'
就这样吧,朋友们。
解决方案 6:
标准库函数urllib.parse.urlsplit()就是您所需要的。以下是 Python3 的示例:
>>> import urllib.parse
>>> o = urllib.parse.urlsplit('https://user:pass@www.example.com:8080/dir/page.html?q1=test&q2=a2#anchor1')
>>> o.scheme
'https'
>>> o.netloc
'user:pass@www.example.com:8080'
>>> o.hostname
'www.example.com'
>>> o.port
8080
>>> o.path
'/dir/page.html'
>>> o.query
'q1=test&q2=a2'
>>> o.fragment
'anchor1'
>>> o.username
'user'
>>> o.password
'pass'
解决方案 7:
如果你认为你的网址有效,那么这将一直有效
domain = "http://google.com".split("://")[1].split("/")[0]
解决方案 8:
这是一个稍微改进的版本:
urls = [
"http://stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url",
"Stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url",
"http://stackoverflow.com/some/folder?test=/questions/9626535/get-domain-name-from-url",
"https://StackOverflow.com:8080?test=/questions/9626535/get-domain-name-from-url",
"stackoverflow.com?test=questions&v=get-domain-name-from-url"]
for url in urls:
spltAr = url.split("://");
i = (0,1)[len(spltAr)>1];
dm = spltAr[i].split("?")[0].split('/')[0].split(':')[0].lower();
print dm
输出
stackoverflow.com
stackoverflow.com
stackoverflow.com
stackoverflow.com
stackoverflow.com
小提琴:https://pyfiddle.io/fiddle/23e4976e-88d2-4757-993e-532aa41b7bf0/?i =true
解决方案 9:
纯字符串操作有什么问题吗:
url = 'http://stackoverflow.com/questions/9626535/get-domain-name-from-url'
parts = url.split('//', 1)
print parts[0]+'//'+parts[1].split('/', 1)[0]
>>> http://stackoverflow.com
如果您希望附加尾部斜杠,请稍微扩展一下此脚本,如下所示:
parts = url.split('//', 1)
base = parts[0]+'//'+parts[1].split('/', 1)[0]
print base + (len(url) > len(base) and url[len(base)]=='/'and'/' or '')
这可能需要稍微优化一下......
解决方案 10:
我知道这是一个老问题,但我今天也遇到了。用一行代码解决了这个问题:
import re
result = re.sub(r'(.*://)?([^/?]+).*', 'g<1>g<2>', url)
解决方案 11:
这有点难懂,但可以urlparse
双向使用:
import urlparse
def uri2schemehostname(uri):
urlparse.urlunparse(urlparse.urlparse(uri)[:2] + ("",) * 4)
奇怪的("",) * 4
是,urlparse 期望的序列恰好是 len(urlparse.ParseResult._fields)
= 6
解决方案 12:
可以通过 re.search() 解决
import re
url = 'https://docs.google.com/spreadsheet/ccc?key=blah-blah-blah-blah#gid=1'
result = re.search(r'^http[s]*://[w.]*', url).group()
print(result)
#result
'https://docs.google.com'
解决方案 13:
您可以简单地使用 urljoin 和相对根 '/' 作为第二个参数:
import urllib.parse
url = 'https://stackoverflow.com/questions/9626535/get-protocol-host-name-from-url'
root_url = urllib.parse.urljoin(url, '/')
print(root_url)
解决方案 14:
这是获取任何域的根 URL 的简单方法。
from urllib.parse import urlparse
url = urlparse('https://stackoverflow.com/questions/9626535/')
root_url = url.scheme + '://' + url.hostname
print(root_url) # https://stackoverflow.com
解决方案 15:
如果它包含少于 3 个斜线,那么您就得到了它,如果没有,那么我们可以找到它之间的发生情况:
import re
link = http://forum.unisoftdev.com/something
slash_count = len(re.findall("/", link))
print slash_count # output: 3
if slash_count > 2:
regex = r'://(.*?)/'
pattern = re.compile(regex)
path = re.findall(pattern, url)
print path
解决方案 16:
获取域名/主机名和来源*
url = 'https://stackoverflow.com/questions/9626535/get-protocol-host-name-from-url'
hostname = url.split('/')[2] # stackoverflow.com
origin = '/'.join(url.split('/')[:3]) # https://stackoverflow.com
*Origin
用于XMLHttpRequest
标题
扫码咨询,免费领取项目管理大礼包!