使用Requests模块Python构建URL

时间:2021-10-14 09:01:39

Is it possible to build a URL using the Requests library for Python?

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

Building a query string is supported but what about building the rest of the URL. Specifically I'd be interested in adding on to the base URL with URL encoded strings:

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

http :// some address.com/api/[term]/

http:// some address.com/api/[term]/

term = 'This is a test'

term ='这是一个测试'

http :// some address.com/api/This+is+a+test/

http:// some address.com/api/This+is+a+test/

This is presumably possible using urllib but it seems like it would be better in Requests. Does this feature exist? If not is there a good reason that it shouldn't?

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

1 个解决方案

#1


36  

requests is basically a convenient wrapper around urllib (and 2,3 and other related libraries).

请求基本上是urllib(以及2,3和其他相关库)的方便包装器。

You can import urljoin(), quote() from requests.compat, but this is essentially the same as using them directly from urllib and urlparse modules:

您可以从requests.compat导入urljoin(),quote(),但这与直接从urllib和urlparse模块中使用它们基本相同:

>>> 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'

#1


36  

requests is basically a convenient wrapper around urllib (and 2,3 and other related libraries).

请求基本上是urllib(以及2,3和其他相关库)的方便包装器。

You can import urljoin(), quote() from requests.compat, but this is essentially the same as using them directly from urllib and urlparse modules:

您可以从requests.compat导入urljoin(),quote(),但这与直接从urllib和urlparse模块中使用它们基本相同:

>>> 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'