【问题标题】:Build a URL using Requests module Python使用请求模块 Python 构建 URL
【发布时间】:2014-05-16 02:13:43
【问题描述】:

是否可以使用 Python 的 Requests 库构建 URL?

支持构建查询字符串,但如何构建 URL 的其余部分。具体来说,我有兴趣使用 URL 编码字符串添加到基本 URL:

http://某个地址.com/api/[term]/

term = '这是一个测试'

http://某个地址.com/api/This+is+a+test/

这可能使用 urllib 是可能的,但在 Requests 中似乎会更好。这个功能存在吗?如果没有,是否有充分的理由不应该这样做?

【问题讨论】:

    标签: python python-requests


    【解决方案1】:

    requests 基本上是urllib(以及 2,3 和其他相关库)的便捷包装。

    您可以从requests.compat 导入urljoin()quote(),但这是essentially the same 直接从urlliburlparse 模块使用它们:

    >>> from requests.compat import urljoin, quote_plus
    >>> url = "http://some-address.com/api/"
    >>> term = 'This is a test'
    >>> urljoin(url, quote_plus(term))
    'http://some-address.com/api/This+is+a+test'
    

    【讨论】:

    • 我喜欢requests.compat.urljoin,因为它适用于 Python 2 和 3。
    • @Addy - 似乎对我很有效。您能否更具体地说明它在哪些情况下不起作用?
    • 无法从requests.compat找到urljoin
    猜你喜欢
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 2015-07-13
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    相关资源
    最近更新 更多