小编典典

从 URL 获取协议 + 主机名

all

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

  • https://docs.google.com/spreadsheet/ccc?key=blah-blah-blah-blah#gid=1
  • https://codingdict.com/questions//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://https://codingdict.com/questions//
  • http://www.example.com
  • https://www.other-domain.example/

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

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

阅读 54

收藏
2022-07-14

共1个答案

小编典典

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

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

# gives
'https://codingdict.com/questions/'
2022-07-14