将参数添加到 Python 中的给定 URL [英] Add params to given URL in Python
问题描述
假设我得到了一个 URL.
它可能已经有 GET 参数(例如 http://example.com/search?q=question
),也可能没有(例如 http://example.com/
).
Suppose I was given a URL.
It might already have GET parameters (e.g. http://example.com/search?q=question
) or it might not (e.g. http://example.com/
).
现在我需要向它添加一些参数,例如 {'lang':'en','tag':'python'}
.在第一种情况下,我将使用 http://example.com/search?q=question&lang=en&tag=python
,在第二种情况下 - http://example.com/search?lang=en&tag=python
.
And now I need to add some parameters to it like {'lang':'en','tag':'python'}
. In the first case I'm going to have http://example.com/search?q=question&lang=en&tag=python
and in the second — http://example.com/search?lang=en&tag=python
.
是否有任何标准方法可以做到这一点?
Is there any standard way to do this?
推荐答案
urllib
和 urlparse
模块有几个怪癖.这是一个工作示例:
There are a couple of quirks with the urllib
and urlparse
modules. Here's a working example:
try:
import urlparse
from urllib import urlencode
except: # For Python 3
import urllib.parse as urlparse
from urllib.parse import urlencode
url = "http://stackoverflow.com/search?q=question"
params = {'lang':'en','tag':'python'}
url_parts = list(urlparse.urlparse(url))
query = dict(urlparse.parse_qsl(url_parts[4]))
query.update(params)
url_parts[4] = urlencode(query)
print(urlparse.urlunparse(url_parts))
ParseResult
,urlparse()
的结果,是只读的,我们需要将其转换为list
,然后才能尝试修改其数据.
ParseResult
, the result of urlparse()
, is read-only and we need to convert it to a list
before we can attempt to modify its data.
这篇关于将参数添加到 Python 中的给定 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!