需求:json
有以下URL地址,截取出 ?後面的參數,並將參數以 ‘key:value’ 的鍵值對形式保存。函數
url="http://xx.xx.xx:8000/get_account.json?page_size=20&page_index=1&user_id=456"url
解法1(利用split()函數):spa
def getParamDict(url): paramList = url.strip().split('?')[1].split('&') paramDict = {} for item in paramList: paramDict[item.split('=')[0]] = item.split('=')[1] return paramDictif __name__ == '__main__': url = "http://xx.xx.xx:8000/get_account.json?page_size=20&page_index=1&user_id=456" print(getParamDict(url))
>>> {'page_size': '20', 'page_index': '1', 'user_id': '456'}
解法2(調用解析模塊 parse)code
def getParamDict(url): from urllib import parse paramDict = parse.parse_qs(parse.urlparse(url).query) return paramDict if __name__ == '__main__': url = "http://xx.xx.xx:8000/get_account.json?page_size=20&page_index=1&user_id=456" print(getParamDict(url))
>>> {'page_size': ['20'], 'page_index': ['1'], 'user_id': ['456']}