一、十六进制与中文
概念
\x开头的编码是十六进制字符,\x后面跟的字符即为十六进制的字符串。
十六进制转中文
1、要转换的类似\xe8\xa7\xa3,且为字符串
info = '\\xe8\\xa7\\xa3\\xe6\\x9e\\x84\\xe6\\x89\\xb9\\xe8\\xaf\\x84\\xe6\\x8e\\xa2\\xe7\\xa7\\x98'
out = bytes(info,'utf-8').decode('unicode_escape').encode('latin1').decode()
print(out)
输出:
解构批评探秘
2、要转换的类似\xe8\xa7\xa3,且为字符串
方法一:
info = '\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xb8\x96\xe7\x95\x8c'
info = info.encode('unicode_escape').decode('utf-8')
out = bytes(info,'utf-8').decode('unicode_escape').encode('latin1').decode()
print(out)
输出:
你好世界
方法二:
from urllib import parse
info = '\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xb8\x96\xe7\x95\x8c'
info = info.encode('unicode_escape').decode('utf-8').replace('\\x', '%')
out = parse.unquote(info)
print(out)
输出:
你好世界
3、为bytes类型
info = b'\xE6\x88\x91\xE6\x98\xAF\xE8\xAF\xB7\xE6\xB1\x82'
info = info.decode('utf-8')
print(info)
输出:
我是请求
二、URL的编码与解码
url编码
1、编码文字
from urllib import parse
print(parse.quote("你好"))
输出:
%E4%BD%A0%E5%A5%BD
2、编码字典
from urllib import parse
args = {
'wd': '你好',
'ie': '哈哈'
}
url = "http://www.baidu.com/s?{}".format(parse.urlencode(args))
print(url)
输出:
http://www.baidu.com/s?wd=%E4%BD%A0%E5%A5%BD&ie=%E5%93%88%E5%93%88
url解码
1、解码字符串
from urllib import parse
print(parse.unquote("http://www.baidu.com/s?wd=%E4%BD%A0%E5%A5%BD&ie=%E5%93%88%E5%93%88"))
输出:
http://www.baidu.com/s?wd=你好&ie=哈哈
2、解码字典
from urllib import parse
params = {
'name': '张三',
'age': 18,
'greet': 'hello'
}
qs = parse.urlencode(params)
print(qs)
result = parse.parse_qs(qs)
print(result)
输出:
name=%E5%BC%A0%E4%B8%89&age=18&greet=hello
{'name': ['张三'], 'age': ['18'], 'greet': ['hello']}
url解析
from urllib import parse
url = 'http://www.baidu.com/s?wd=python&username=abc#1'
result = parse.urlparse(url)
print('scheme:', result.scheme)
print('netloc:', result.netloc)
print('path:', result.path)
print('params:', result.params)
print('query:', result.query)
print('fragment:', result.fragment)
输出:
scheme: http
netloc: www.baidu.com
path: /s
params:
query: wd=python&username=abc
fragment: 1
url提取查询参数
方法一:
from urllib import parse
url = 'http://www.baidu.com/s?wd=python&username=abc#1'
def get_query(url):
result = parse.urlparse(url)
querys = parse.parse_qs(result.query)
querys = {k: v[0] for k, v in querys.items()}
return querys
print(get_query(url))
输出:
{'wd': 'python', 'username': 'abc'}
方法二:使用模块furl 安装
pip install furl
使用
from furl import furl
f = furl("http://www.baidu.com/s?wd=python&username=abc#over")
print(f.path)
print(f.scheme)
print(f.fragment)
print(f.args['wd'])
print(f.args['username'])
输出:
/s
http
over
python
abc
unicode与中文
unicode转中文:类型1
s = '\\u9500\\u552e'
print(json.loads(f'"{s}"'))
print(s.encode('utf-8').decode("unicode_escape"))
输出:
销售
销售
unicode转中文:类型2
i = '\u751F\u5316\u5371\u673A'
print(str(i))
输出:
生化危机
|