对python中url参数编码与解码的实例详解

yipeiwu_com7年前Python基础

一、简介

在python中url,对于中文等非ascii码字符,需要进行参数的编码与解码。

二、关键代码

1、url编码

对字符串编码用urllib.parse包下的quote(string, safe='/', encoding=None, errors=None)方法。

对json格式的参数名和值编码,用urllib.parse包下的

urlencode(query, doseq=False, safe='', encoding=None, errors=None, quote_via=quote_plus)方法。

2、url解码

解码用urllib.parse包下的unquote(string, encoding='utf-8', errors='replace')方法。

三、代码实例

from urllib.parse import quote, unquote, urlencode


def main():
 my_data = '好好学习'

 # url编码
 encode_data = quote(my_data)
 print("encode_data : %s " % encode_data)
 # url解码
 decode_data = unquote(encode_data)
 print("decode_data : %s " % decode_data)

 my_query = {'conent': '天天向上'}
 # url参数编码
 encode_query = urlencode(my_query)
 print("encode_query : %s " % encode_query)
 # url参数解码
 decode_query = unquote(encode_query)
 print("decode_query : %s " % decode_query)
 encode_url = 'http://127.0.0.1?'+encode_query
 # url解码
 decode_url = unquote(encode_url)
 print("decode_url : %s " % decode_url)


if __name__ == '__main__':
 main()

输出:

encode_data : %E5%A5%BD%E5%A5%BD%E5%AD%A6%E4%B9%A0 
decode_data : 好好学习 
encode_query : conent=%E5%A4%A9%E5%A4%A9%E5%90%91%E4%B8%8A 
decode_query : conent=天天向上 
decode_url : http://127.0.0.1?conent=天天向上 

以上这篇对python中url参数编码与解码的实例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

centos6.7安装python2.7.11的具体方法

1. 查看本机系统及python版本 # cat /etc/redhat-release CentOS release 6.7 (Final) 查看CentOS release 6.7...

python 调用有道api接口的方法

python 调用有道api接口的方法

初学python ,研究了几天,写了一个python 调用 有道api接口程序 效果看下图: 申明:代码仅供和我一样的初学者学习交流 有道api申请地址http://fanyi.you...

Python中type的构造函数参数含义说明

测试代码如下: 复制代码 代码如下:  class ModelMetaClass(type):      def __new__(cls...

python读文件保存到字典,修改字典并写入新文件的实例

实例如下所示: tcode={} transcode={} def GetTcode(): #从文本中获取英文对应的故障码,并保存在tcode字典(故障码文本样例:oxff,0xff...

使用TensorFlow对图像进行随机旋转的实现示例

使用TensorFlow对图像进行随机旋转的实现示例

在使用深度学习对图像进行训练时,对图像进行随机旋转有助于提升模型泛化能力。然而之前在做旋转等预处理工作时,都是先对图像进行旋转后保存到本地,然后再输入模型进行训练,这样的过程会增加工作量...