python 将字典转成url参数

from urllib.parse import urlencode
params = {'wd': 'python', 'ie': 'utf-8'}
result = urlencode(params) # wd=python&ie=utf-8

将url参数转成字典

from urllib.parse import parse_qs, urlparse
url = 'https://www.baidu.com/s?&wd=python&ie=utf-8'
# 提取url参数
query = urlparse(url).query  # wd=python&ie=utf-8
# 将字符串转换为字典
params = parse_qs(query)  # {'wd': ['python'], 'ie': ['utf-8']}
"""所得的字典的value都是以列表的形式存在,若列表中都只有一个值"""
result = {key: params[key][0] for key in params}  # {'wd': 'python', 'ie': 'utf-8'}

 

上一篇:洛谷 P5162 WD与积木【多项式求逆】


下一篇:三个爬虫的小栗子