2012-04-27 181 views
1

我想爲我的組織網站的任何URL組成一個等效的調試URL。我有Python函數來做到這一點:如何在Python中注入URL查詢字符串參數?

import urlparse 
import urllib 

def compose_debug_url(input_url): 
    input_url_parts = urlparse.urlsplit(input_url) 
    input_query = input_url_parts.query 
    input_query_dict = urlparse.parse_qs(input_query) 

    modified_query_dict = dict(input_query_dict.items() + [('debug', 'sp')]) 
    modified_query = urllib.urlencode(modified_query_dict) 
    modified_url_parts = (
     input_url_parts.scheme, 
     input_url_parts.netloc, 
     input_url_parts.path, 
     modified_query, 
     input_url_parts.fragment 
    ) 

    modified_url = urlparse.urlunsplit(modified_url_parts) 

    return modified_url 



print compose_debug_url('http://www.example.com/content/page?name=john&age=35') 
print compose_debug_url('http://www.example.com/') 

如果你運行上面的代碼,你應該看到輸出:

http://www.example.com/content/page?debug=sp&age=%5B%2735%27%5D&name=%5B%27john%27%5D 
http://www.example.com/?debug=sp 

相反,我想到:

http://www.example.com/content/page?debug=sp&age=35&name=john 
http://www.example.com/?debug=sp 

這是因爲urlparse.parse_qs回報字符串字典的列表,而不是字符串字符串的字典。

有沒有另一種方法可以更簡單地在Python中做到這一點?

回答

1

urlparse.parse_qs返回列表的每個鍵的值。在你的例子中它是 {'age': ['35'], 'name': ['john']},而你想要的是{'age': '35', 'name': 'john'}

由於您使用的鍵,值標準桿爲一個列表,使用urlparse.parse_qsl

modified_query_dict = dict(urlparse.parse_qsl(input_query) + [('debug', 'sp')]) 
+0

謝謝。 'urlparse.parse_qsl'表現得如我所料。 – 2012-04-27 15:53:00

1

晚的答案,但urlencode需要doseq參數可以用來拼合列表。

相關問題