【问题标题】:How do I get urljoin to work as expected in Python?如何让 urljoin 在 Python 中按预期工作?
【发布时间】:2015-07-28 16:40:23
【问题描述】:

假设我有以下网址:

url = https://www.example.com/thing1/thing2/thing3
next_thing = thing4

我想要以下网址:

https://www.example.com/thing1/thing2/thing3/thing4

当我尝试时

>>> urlparse.urljoin(url,next_thing) 

我得到以下结果:

https://www.example.com/thing1/thing2/thing4

为什么thing3 被删掉了?我该如何解决?非常感谢!

【问题讨论】:

    标签: python url urlparse


    【解决方案1】:

    URL 中缺少尾部斜杠,附加它以使 thing3 成为“目录”:

    >>> from urlparse import urljoin
    >>> url = "https://www.example.com/thing1/thing2/thing3"
    
    >>> urljoin(url, "thing4")
    'https://www.example.com/thing1/thing2/thing4'
    >>> urljoin(url + "/", "thing4")
    'https://www.example.com/thing1/thing2/thing3/thing4'
    

    【讨论】:

    • 有趣!谢谢@alecxe!如果可行,我会试试这个并喜欢/接受你的答案。同时,您知道为什么斜线会有所不同吗?
    • @codycrossley 不带斜线 thing3 被认为是“文件名”,此处提供了一些解释:stackoverflow.com/a/4317446/771848。很高兴它有帮助。
    • 啊,有道理!非常感谢!
    【解决方案2】:

    不确定,但认为这可能是您正在寻找的。​​p>

    url = 'https://www.example.com/thing1/thing2/thing3'
    next_thing = 'thing4'
    test = url + next_thing
    print(test)
    

    出来:

    https://www.example.com/thing1/thing2/thing3/thing4
    

    【讨论】:

    • 我同意这会起作用,这是我之前使用的,但我现在尝试坚持使用 urlparse.urljoin 方法。非常感谢您的反馈!
    • 抱歉没有意识到这一点!
    • 别担心! =] 不过,我真的很感谢您的反馈!
    • 这实际上会导致https://www.example.com/thing1/thing2/thing3thing4,注意thing3thing4之间缺少的斜线。
    猜你喜欢
    • 2011-02-01
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    相关资源
    最近更新 更多