如何使用Python将自定义参数添加到URL查询字符串?

如何使用Python将自定义参数添加到URL查询字符串?,第1张

如何使用Python将自定义参数添加到URL查询字符串

您可以使用

urlsplit()
urlunsplit()
分解并重建URL,然后
urlenpre()
在解析的查询字符串上使用:

from urllib import urlenprefrom urlparse import parse_qs, urlsplit, urlunsplitdef set_query_parameter(url, param_name, param_value):    """Given a URL, set or replace a query parameter and return the    modified URL.    >>> set_query_parameter('http://example.com?foo=bar&biz=baz', 'foo', 'stuff')    'http://example.com?foo=stuff&biz=baz'    """    scheme, netloc, path, query_string, fragment = urlsplit(url)    query_params = parse_qs(query_string)    query_params[param_name] = [param_value]    new_query_string = urlenpre(query_params, doseq=True)    return urlunsplit((scheme, netloc, path, new_query_string, fragment))

如下使用它:

>>> set_query_parameter("/scr.cgi?q=1&ln=0", "SOMESTRING", 1)'/scr.cgi?q=1&ln=0&SOMESTRING=1'


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5647863.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存