Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法。对html进行编码Python 2.x中可以使用cgi中escape,Python 3.x中可以使用html中esape。对url进行编码Python 2.x中可以使用urllib,Python 3.x中可以使用urllib中parse。

1、Base64的编码与解码

1)Python2

# -*- coding: UTF-8 -*-  
import base64

s = 'www.cjavapy.com'
b = base64.b64encode(s)
print 'b为:', b

c = base64.b64decode(b)
print 'c为:', c

2)Python3

import base64

s = 'www.cjavapy.com'
b = base64.b64encode(s.encode('utf-8')).decode('utf-8')
print(b)

c = base64.b64decode(b.encode('utf-8')).decode('utf-8')
print(c)

2、Html的编码与解码

1)Html编码

try:
    from html import escape  # python 3.x
except ImportError:
    from cgi import escape  # python 2.x
 
print(escape('<a href="https://www.cjavapy.com">CJAVAPY编程之路</a>'))

2)Html解码

try:
    from html import unescape  # python 3.4+
    from html import escape  # python 3.x
except ImportError:
    try:
        from html.parser import HTMLParser  # python 3.x (<3.4)
    except ImportError:
        from HTMLParser import HTMLParser  # python 2.x
    unescape = HTMLParser().unescape
value = escape('<a href="https://www.cjavapy.com">CJAVAPY编程之路</a>')
print(value) 
print(unescape(value))

3、url字符串编码与解码

1)Python2

# -*- coding: UTF-8 -*-  
import urllib

# python2中
#编码
value = {
                '': '//?$&编程之路'
           }
data = urllib.urlencode(value)  #  # 其中value为所需要编码的数据,并且只能为字典
print(data)
#解码
print(urllib.unquote(data))

2)Python3

from urllib import parse

# python3中
#编码
value = {
          '': '//?$&编程之路',
        }
data = parse.quote(str(value))
print(data)

#解码
print(parse.unquote(data))

推荐文档