
您可以使用
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'欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)