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

yipeiwu_com6年前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设计】。

相关文章

简介Python的collections模块中defaultdict类型的用法

defaultdict 主要用来需要对 value 做初始化的情形。对于字典来说,key 必须是 hashable,immutable,unique 的数据,而 value 可以是任意的...

Django实现全文检索的方法(支持中文)

PS: 我的检索是在文章模块下 forum/article 第一步:先安装需要的包: pip install django-haystack pip install whoosh p...

Python中Random和Math模块学习笔记

由于最近经常使用到Python中random,math和time``datetime模块, 所以决定花时间系统的学习一下 1. math模块 math中的函数不可以用于太过复杂的数的运算...

Python使用add_subplot与subplot画子图操作示例

Python使用add_subplot与subplot画子图操作示例

本文实例讲述了Python使用add_subplot与subplot画子图操作。分享给大家供大家参考,具体如下: 子图:就是在一张figure里面生成多张子图。 Matplotlib对象...

浅析python,PyCharm,Anaconda三者之间的关系

一、它们是什么? 1.python Python是一种跨平台的计算机程序设计语言,简单来说,python就是类似于C,Java,C++等,一种编程语言。 2.Anaconda Anaco...