我正试图从不同的部分形成url,并且很难理解这种方法的行为。例如:
Python 3.x
from urllib.parse import urljoin
>>> urljoin('some', 'thing')
'thing'
>>> urljoin('http://some', 'thing')
'http://some/thing'
>>> urljoin('http://some/more', 'thing')
'http://some/thing'
>>> urljoin('http://some/more/', 'thing') # just a tad / after 'more'
'http://some/more/thing'
urljoin('http://some/more/', '/thing')
'http://some/thing'
你能解释一下这种方法的具体行为吗?
最好的方法(对我来说)是第一个参数,
base
就像你在浏览器中的页面一样。第二个参数url
是该页上锚的href。结果是最后一个url,如果您单击它,您将被定向到该url。这个很有道理,请给我描述一下。尽管人们希望基础包括一个方案和域。
如果你在一个vhost some上,并且有一个类似
<a href='thing'>Foo</a>
的锚,那么链接将带你到http://some/thing
我们在
some/more
上,因此thing
的相对链接将带我们到/some/thing
在这里,我们不在
some/more
上,我们在some/more/
上,这是不同的。现在,我们的相对链接将带我们到some/more/thing
最后。如果在
some/more/
上,并且该ref是/thing
,则将链接到some/thing
。否则,urllib.parse.urljoin(base,url)将
它获取第一个参数(base)的路径,去掉最后一个/之后的部分,并与第二个参数(url)连接。
如果url以/开头,则它将scheme和base的netloc与url连接起来
相关问题 更多 >
编程相关推荐