从URL获取协议+主机名 [英] Get protocol + host name from URL

查看:141
本文介绍了从URL获取协议+主机名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Django应用中,我需要在 request.META.get('HTTP_REFERER')的引荐来源网址中获取主机名及其协议,以便从URL像这样:

In my Django app, I need to get the host name from the referrer in request.META.get('HTTP_REFERER') along with its protocol so that from URLs like:

  • 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.com/whatever/blah/blah/?v1=0&v2=blah+blah ...

我应该得到:

  • https://docs.google.com/
  • https://stackoverflow.com/
  • http://www.example.com
  • https://www.other-domain.com/

我查看了其他相关问题并发现了有关urlparse的信息,

I looked over other related questions and found about urlparse, but that didn't do the trick since

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


推荐答案

您应该可以使用 urlparse (文档: python2 python3 ):

You should be able to do it with urlparse (docs: 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/'

这篇关于从URL获取协议+主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆