【问题标题】:Is it possible to have an absolute href attribute with no scheme?是否可以有一个没有方案的绝对 href 属性?
【发布时间】:2015-03-13 09:01:09
【问题描述】:
我正在尝试寻找一种方法来测试一个 URL 在 Python 中是绝对的还是相对的。在 HTML 标记的 href 属性中,是否缺少足以将 URL 标记为相对 URL 的方案(例如 http、ftp 等),或者是否可以在没有明确指定方案的情况下将绝对 URL 作为 href 属性(例如“www.google.com”)?我正在使用urlparse.urlparse('some url').scheme 获取方案。
【问题讨论】:
标签:
python
html
tags
uri
url-scheme
【解决方案1】:
如果您不包含 URI 方案(http://、https://、// 等),那么浏览器将假定它是一个相对 URL。
您应该注意脚本的相对于方案的 URL,例如 //www.google.com。简而言之,您应该寻找一个双正斜杠// 来确定一个网址是否会被视为相对网址。
【解决方案2】:
根据RFC 3986:
<a href="//example.com/page.html">Link</a>
来源和更多信息:https://stackoverflow.com/a/550073/2454476
在python中:
$ python
Python 2.7.3 (default, Mar 18 2014, 05:13:23)
>>> from urlparse import urlparse;
>>> urlparse('//example.com/page.html');
ParseResult(scheme='', netloc='example.com', path='/page.html', params='', query='', fragment='')