問題描述
在python中解析url以提取參數 (Parsing url in python to extract parameters)
我在 python 中有一個 URL,如
localhost:8080&id=123&id=345&name=john
是否有一個庫可以解析這個並獲取所有參數的鍵值對?因為我想再次使用說 id
feild 將 url 創建為初始參數的組合,所以我將有兩個新的 URL。
localhost:8080&id=123&name=john
和 localhost:8080&id=345&name=john
我在 python 2.7 中使用此代碼,但它並沒有帶來兩個 id 的
parse_url = urlparse(url)
query_dict = dict(parse_qsl(parse_url.query))
print query_dict
參考解法
方法 1:
I think you could accomplish this with a regex
import re
components = [re.split(":|=", component) for component in <url>.split("&")]
url_dict = {component[0]: component[1] for component in components}
(by John Constantine、mattyx17)