假设我获得了一个URL
它可能已经有GET参数(例如http://example.com/search?q=question
),也可能没有(例如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
。
有没有标准方法可以做到这一点?
答案 0 :(得分:154)
urllib
和urlparse
模块存在一些怪癖。这是一个有效的例子:
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()
,is read-only的结果,在我们尝试修改数据之前,我们需要将其转换为list
。
答案 1 :(得分:39)
我对此页面上的所有解决方案都不满意(来了,我们最喜欢的复制粘贴的东西在哪里?)所以我根据这里的答案编写了自己的解决方案。它试图完成并且更加Pythonic。我在参数中添加了 dict 和 bool 值的处理程序,以便更加消费者( JS )友好,但它们是可选的,你可以放弃它们。
测试1:添加新参数,处理Arrays和Bool值:
url = 'http://stackoverflow.com/test'
new_params = {'answers': False, 'data': ['some','values']}
add_url_params(url, new_params) == \
'http://stackoverflow.com/test?data=some&data=values&answers=false'
测试2:重写现有的args,处理DICT值:
url = 'http://stackoverflow.com/test/?question=false'
new_params = {'question': {'__X__':'__Y__'}}
add_url_params(url, new_params) == \
'http://stackoverflow.com/test/?question=%7B%22__X__%22%3A+%22__Y__%22%7D'
代码本身。我试图详细描述它:
from json import dumps
try:
from urllib import urlencode, unquote
from urlparse import urlparse, parse_qsl, ParseResult
except ImportError:
# Python 3 fallback
from urllib.parse import (
urlencode, unquote, urlparse, parse_qsl, ParseResult
)
def add_url_params(url, params):
""" Add GET params to provided URL being aware of existing.
:param url: string of target URL
:param params: dict containing requested params to be added
:return: string with updated URL
>> url = 'http://stackoverflow.com/test?answers=true'
>> new_params = {'answers': False, 'data': ['some','values']}
>> add_url_params(url, new_params)
'http://stackoverflow.com/test?data=some&data=values&answers=false'
"""
# Unquoting URL first so we don't loose existing args
url = unquote(url)
# Extracting url info
parsed_url = urlparse(url)
# Extracting URL arguments from parsed URL
get_args = parsed_url.query
# Converting URL arguments to dict
parsed_get_args = dict(parse_qsl(get_args))
# Merging URL arguments dict with new params
parsed_get_args.update(params)
# Bool and Dict values should be converted to json-friendly values
# you may throw this part away if you don't like it :)
parsed_get_args.update(
{k: dumps(v) for k, v in parsed_get_args.items()
if isinstance(v, (bool, dict))}
)
# Converting URL argument to proper query string
encoded_get_args = urlencode(parsed_get_args, doseq=True)
# Creating new parsed result object based on provided with new
# URL arguments. Same thing happens inside of urlparse.
new_url = ParseResult(
parsed_url.scheme, parsed_url.netloc, parsed_url.path,
parsed_url.params, encoded_get_args, parsed_url.fragment
).geturl()
return new_url
请注意,可能存在一些问题,如果您找到一个问题请告诉我,我们会更好地做这件事
答案 2 :(得分:32)
如果字符串可以包含任意数据,则需要使用URL编码(例如,“&符”,“斜杠”等字符需要编码)。
查看urllib.urlencode:
>>> import urllib
>>> urllib.urlencode({'lang':'en','tag':'python'})
'lang=en&tag=python'
答案 3 :(得分:18)
您还可以使用furl模块https://github.com/gruns/furl
>>> from furl import furl
>>> print furl('http://example.com/search?q=question').add({'lang':'en','tag':'python'}).url
http://example.com/search?q=question&lang=en&tag=python
答案 4 :(得分:9)
是:使用urllib。
来自文档中的examples:
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
>>> print f.geturl() # Prints the final URL with parameters.
>>> print f.read() # Prints the contents
答案 5 :(得分:8)
如果您使用requests lib:
import requests
...
params = {'tag': 'python'}
requests.get(url, params=params)
答案 6 :(得分:7)
基于this回答,简单案例的单行(Python 3代码):
from urllib.parse import urlparse, urlencode
url = "https://stackoverflow.com/search?q=question"
params = {'lang':'en','tag':'python'}
url += ('&' if urlparse(url).query else '?') + urlencode(params)
或:
url += ('&', '?')[urlparse(url).query == ''] + urlencode(params)
答案 7 :(得分:7)
将其外包给经过测试的战斗requests library。
我将这样做:
from requests.models import PreparedRequest
url = 'http://example.com/search?q=question'
params = {'lang':'en','tag':'python'}
req = PreparedRequest()
req.prepare_url(url, params)
print(req.url)
答案 8 :(得分:6)
我喜欢Łukasz版本,但由于urllib和urllparse函数在这种情况下使用起来有些尴尬,我认为做这样的事情更直接:
params = urllib.urlencode(params)
if urlparse.urlparse(url)[4]:
print url + '&' + params
else:
print url + '?' + params
答案 9 :(得分:3)
使用各种urlparse
功能拆分现有网址urllib.urlencode()
,然后urlparse.urlunparse()
将所有网页重新组合在一起。
或者只是取urllib.urlencode()
的结果并将其连接到URL。
答案 10 :(得分:3)
又一个答案:
def addGetParameters(url, newParams):
(scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
queryList = urlparse.parse_qsl(query, keep_blank_values=True)
for key in newParams:
queryList.append((key, newParams[key]))
return urlparse.urlunparse((scheme, netloc, path, params, urllib.urlencode(queryList), fragment))
答案 11 :(得分:2)
我发现这比两个最重要的答案更为优雅:
from urllib.parse import urlencode, urlparse, parse_qs
def merge_url_query_params(url: str, additional_params: dict) -> str:
url_components = urlparse(url)
original_params = parse_qs(url_components.query)
# Before Python 3.5 you could update original_params with
# additional_params, but here all the variables are immutable.
merged_params = {**original_params, **additional_params}
updated_query = urlencode(merged_params, doseq=True)
# _replace() is how you can create a new NamedTuple with a changed field
return url_components._replace(query=updated_query).geturl()
assert merge_url_query_params(
'http://example.com/search?q=question',
{'lang':'en','tag':'python'},
) == 'http://example.com/search?q=question&lang=en&tag=python'
我最不喜欢的最重要的事情(尽管如此)还是不错的:
query
在URL组件中的索引ParseResult
我的回答不好的是使用解压缩的dict
看起来很神奇,但是由于我对可变性的偏见,我更喜欢更新现有的字典。
答案 12 :(得分:1)
在python 2.5中
import cgi
import urllib
import urlparse
def add_url_param(url, **params):
n=3
parts = list(urlparse.urlsplit(url))
d = dict(cgi.parse_qsl(parts[n])) # use cgi.parse_qs for list values
d.update(params)
parts[n]=urllib.urlencode(d)
return urlparse.urlunsplit(parts)
url = "http://stackoverflow.com/search?q=question"
add_url_param(url, lang='en') == "http://stackoverflow.com/search?q=question&lang=en"
答案 13 :(得分:1)
以下是我实施它的方式。
import urllib
params = urllib.urlencode({'lang':'en','tag':'python'})
url = ''
if request.GET:
url = request.url + '&' + params
else:
url = request.url + '?' + params
像魅力一样工作。但是,我希望有一种更清洁的方式来实现它。
实现上述方法的另一种方法是将其放在方法中。
import urllib
def add_url_param(request, **params):
new_url = ''
_params = dict(**params)
_params = urllib.urlencode(_params)
if _params:
if request.GET:
new_url = request.url + '&' + _params
else:
new_url = request.url + '?' + _params
else:
new_url = request.url
return new_ur
答案 14 :(得分:1)
python3
,我想是自我解释
from urllib.parse import urlparse, urlencode, parse_qsl
url = 'https://www.linkedin.com/jobs/search?keywords=engineer'
parsed = urlparse(url)
current_params = dict(parse_qsl(parsed.query))
new_params = {'location': 'United States'}
merged_params = urlencode({**current_params, **new_params})
parsed = parsed._replace(query=merged_params)
print(parsed.geturl())
# https://www.linkedin.com/jobs/search?keywords=engineer&location=United+States