天天看點

url參數和字典的互相轉化

url參數和字典的互相轉化

目标 url:https://www.baidu.com/s?&wd=python&ie=utf-8

将字典轉成url參數

# 使用urllib.parse的urlencode方法,将字典對象傳入傳回标準的url參數格式字元串
from urllib.parse import urlencode

# 1. 将字典轉成url參數
def dict_to_query(url,params_dict):
    result = urlencode(params_dict)
    url_join = url+"?"+result
    return url_join

url = "https://www.baidu.com"
params_dict = {'wd': 'python', 'ie': 'utf-8'}
url_join = dict_to_query(url,params_dict)
print(url_join) # https://www.baidu.com?wd=python&ie=utf-8
           

将url參數轉成字典

from urllib.parse import urlparse,parse_qs

# 2. 将url參數轉成字典
def url_to_dict(url):
    # 提取url參數
    query = urlparse(url).query
    # 将字元串轉換為字典
    # 所得的字典的value都是以清單的形式存在,若清單中都隻有一個值
    params = parse_qs(query)
    result = {key: params[key][0] for key in params}
    return result

url="https://www.baidu.com/s?&wd=python&ie=utf-8"
params_dict = url_to_dict(url)
print(params_dict) # {'wd': 'python', 'ie': 'utf-8'}