您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

您可以使用@L_502_0@和urlunsplit()分解并重建URL,然后urlencode()在解析的查询字符串上使用:

from urllib import urlencode
from urlparse import parse_qs, urlsplit, urlunsplit

def 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 = urlencode(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'
python 2022/1/1 18:25:52 有408人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶