在网页爬取信息之后,response.text
得到的是字符串类型,response.content
得到的是byte类型
这些数据会遇到解码和编码的问题,现在对这些进行统一总结
import json
首先需要对把爬取后的内容,用type()
得到其数据类型
r/R
表示raw string(原始字符串)
str1 = "Hello\nWorld"
str2 = r"Hello \n World"
print(str1)
print(str2)
输出结果如下:
Hello
World
Hello \n World
u/U
表示unicode string(unicode编码字符串),Python 3中所有字符串默认都是unicode字符串,显示中文用"utf-8"
str1 = '\u4f60\u597d\u4e16\u754c'
str2 = u'\u4f60\u597d\u4e16\u754c'
print(str1)
print(str2)
输出结果如下:
你好世界
你好世界
b/B
表示byte string(转换成bytes类型)
str1 = 'hello world'
str2 = b'hello world'
print(type(str1))
print(type(str2))
输出结果如下:
<class 'str'>
<class 'bytes'>
针对不同类型的数据,对元数据进行解码和编码
方法一、使用unicode_escape
解码,bytes类型的数据
unicode = b'\\u4f60\\u597d'
re = unicode.decode("unicode_escape")
print(re)
输出结果:你好
unicode = '\\u4f60\\u597d'
re = unicode.encode('utf-8').decode('unicode_escape')
print(re)
输出结果:你好
方法二:使用encode()
方法转换,再调用bytes.decode()
转换为字符串形式,raw string原始字符串类型
s = r'\u4f60\u597d'
print(s.encode().decode("unicode_escape"))
输出结果:你好
方法三: 使用json.loads
解码(为json格式),针对str字符串类型,转换为json
import json
str = '\u4eac\u4e1c\u653e\u517b\u7684\u722c\u866b'
print(json.loads('"%s"' % str))
输出结果:仍为字符串,处理数据的编码\u4eac\u4e1c\u653e\u517b\u7684\u722c\u866b
或者使用json.loads(str)
,处理字符串为json格式,得到的数据类型为dict字典类型
str = '{"data1": "name1", "data2": "name2"}'
json_str = json.loads(str)
print(json_str)
这样Python会报错,json.loads
必须是json格式,键值对需要是双引号,对格式有强要求
str = '{"data1": "name1", "data2": 2}' # 键值使用双引号
json_str = json.loads(str)
print(json_str) # 得到的数据为dict类型
方法四:使用eval
(遇到Unicode是通过requests.text
在网上爬取的时候),requests.text
得到的数据类型为str类型
str = '\u4eac\u4e1c\u653e\u517b\u7684\u722c\u866b'
re = eval("u"+"\'"+str+"\'")
print(type(re)) # 得到的是字符串类型
方法五:得到byte类型的数据,使用decode()
进行解码
str和bytes类型之间的相互转换
b = b"\xe6\x96\xb0\xe5\x86\xa0\xe7\x96\xab\xe6\x83\x85\xe9\x98\xb2\xe6\x8a\xa4\xe6\x8c\x87\xe5\x8d\x97"
text = b.decode()
print(text) # 得到的是字符串类型