对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 PyInstaller库基本使用方法分析

Python PyInstaller库基本使用方法分析

本文实例讲述了Python PyInstaller库基本使用方法。分享给大家供大家参考,具体如下: 概述 将.py源码转换成无需源代码的可执行文件 .py文件 -> PyIns...

python 获取et和excel的版本号

复制代码 代码如下:#-*- coding:utf-8 -*- from win32com.client import Dispatch if __name__ == '__main__...

Django处理文件上传File Uploads的实例

HttpRequest.FILES 表单上传的文件对象存储在类字典对象request.FILES中,表单格式需为multipart/form-data <form enctyp...

Python3 无重复字符的最长子串的实现

Python3 无重复字符的最长子串的实现

题目: 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 示例: 示例 1: 输入: “abcabcbb” 输出: 3 解释: 因为无重复字符的最长子串是 “abc”...

django数据模型(Model)的字段类型解析

字段类型(Field types) 1、AutoField 它是一个根据 ID 自增长的 IntegerField 字段。通常,你不必直接使用该字段。如果你没在别的字段上指定主 键,Dj...