Python request..compat.urljoin-当URL不包含一个访问方法时,添加一个访问方法

时间:2019-02-25 17:46:04

标签: python https python-requests

以下是我尝试将https://附加到URL的两种方法。由于某种原因,urljoin方法给出了奇怪的输出:

from requests.compat import urljoin

host = 'abc.def.com'
host2 = host

# brute-force string method
if not host.startswith('https://'):
    host = 'https://' + host  # Add schema
if host.endswith('/'):
    host = host[:-1]          # Strip /
print('Stringy way', host)

# nice library method? Doesn't quite work
print('urljoin    ', urljoin('https://', host2))

我看到的输出带有三个///奇怪的字符

Stringy way https://abc.def.com
urljoin     https:///abc.def.com

我也得到了其他变体的无效结果:

print('urljoin #2 ', urljoin('https:/', host2))
print('urljoin #3 ', urljoin('https:', host2))
print('urljoin #4 ', urljoin('https', host2))

给予:

urljoin #2  https:///abc.def.com
urljoin #3  https:///abc.def.com
urljoin #4  abc.def.com

这是使用错误的功能吗?

2 个答案:

答案 0 :(得分:1)

您可以利用urllib.parse.urlunsplit()来组成URL:

from urllib.parse import urlunsplit

print(urlunsplit(("https", "abc.def.com", "", "", "")))

结果:

https://abc.def.com

它将元组作为输入,与urlsplit()的输出匹配,并具有元组的以下属性:

enter image description here

答案 1 :(得分:0)

urljoin函数通常用于将href锚附加到现有url。示例:

from requests.compat import urljoin
url = 'https://abc.def.com'
href = '364'
urljoin(url, href)

我得到输出:-

'https://abc.def.com/364'

但是,如果我想用'https://'填写我的网址,我宁愿使用:-

from requests.compat import urljoin
url = 'abc.def.com'
host = ('https://'+ url)
print(host)

我的输出是:

https://abc.def.com

我希望这会有所帮助。