从URL获取协议+主机名

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

  • https://docs.google.com/spreadsheet/ccc?key=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=废话+废话

我应该得到:

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

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

&gt&燃气轮机&燃气轮机;urlparse(request.META.get('HTTP\u REFERER')).hostname
“docs.google.com”

您应该能够使用urlparse(文档:python2,python3)完成此操作:

从urllib.parse导入urlparse
#从URLPRASE导入URLPRASE#Python 2
parsed_uri=urlparse('http://stackoverflow.com/questions/1234567/blah-blah-blah-blah' )
result='{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
打印(结果)
#给予
'http://stackoverflow.com/'

发表评论