2010-11-27 153 views

回答

9

使用urlsplit()提取查詢字符串,parse_qsl()解析它(或parse_qs()如果你不關心參數順序),添加新的參數,urlencode()把它放回一個查詢字符串,urlunsplit()將其重新導回到單個URL中,然後重定向客戶端。

0
import urllib 
url = "/scr.cgi?q=1&ln=0" 
param = urllib.urlencode({'SOME&STRING':1}) 
url = url.endswith('&') and (url + param) or (url + '&' + param) 

the docs

67

您可以使用urlsplit()urlunsplit()掰開重建一個URL,然後在解析的查詢字符串中使用urlencode()

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

我用它作爲分頁,它像一個魅力工作。謝謝! – Jabba 2015-06-04 17:21:32

+0

雖然這已經有幾年了,但我仍然覺得有必要指出這一點,因爲這個問題出現在谷歌搜索的首頁:如果你關心參數的順序(我假設你這樣做,因爲doseq =真正的部分),你應該使用`parse_qsl()`,而不是`parse_qs()` - 前者返回一個元組列表,而後者返回一個字典,這是**不保證保持順序當迭代時。然後,可以通過query_params.append((param_name,param_value))`來添加一個參數。 – mhouglum 2017-09-29 17:19:24

0

您可以使用Python:

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)) 

如下使用它url操作庫furl

import furl 
f = furl.furl("/scr.cgi?q=1&ln=0") 
f.args['SOMESTRING'] = 1 
print(f.url) 
相關問題