python
encode
decode
编码
decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode(‘gb2312’),表示将gb2312编码的字符串str1转换成unicode编码。
encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode(‘gb2312’),表示将unicode编码的字符串str2转换成gb2312编码。
当我们想获取网页源代码,并且希望能够以html后缀或者其他格式保存文件的时候,如果不进行编码,那么保存得到的文件在遇到中文时就会出现异常,不便于我们对数据的处理。
首先说一下使用requests请求得到源代码的处理办法。
经过我无数次的实践,发现通过get请求得到的源代码都是“byte”类型,所以每当想都过write写入到文件中时总是会报错。如下:
-
#coding=utf-8
-
imp
ort requests
-
-
r = requests.get('http://www.baidu.com')
-
-
print(type(r.text))
-
with open('baidu.html','w') as f:
-
f.write(r.text)
输出结果
-
>>>
-
<class 'str'>
-
Traceback (most recent call last):
-
File "C:\Users\14356_000\Desktop\test.py", line 8, in <module>
-
f.write(r.text)
-
UnicodeEncodeError: 'gbk' codec can't encode character '\xbb' in position 25364: illegal multibyte sequence
解决办法:示例代码如下
-
-
imp
ort requests
-
imp
ort chardet
-
-
r = requests.get('http://www.baidu.com')
-
content = r.text
-
print(type(content))
-
print(chardet.detect(content.encode('utf-8')))
-
with open('baidu.html','w',encoding='utf-8') as f:
-
f.write(content.encode('utf-8').decode('utf-8'))
注意chardet是用来查看文字编码类型的,之前想使用下面代码直接查看content的编码类型,但是报错。
-
...
-
...
-
print(chardet.detect(content))
-
-
>>>
-
Traceback (most recent call last):
-
File "C:\Users\14356_000\Desktop\test.py", line 8, in <module>
-
print(chardet.detect(content))
-
File "C:\Python35\lib\site-packages\chardet\__init__.py", line 25, in detect
-
raise ValueError('Expected a bytes object, not a unicode object')
-
ValueError: Expected a bytes object, not a unicode object
因此需要先通过encode,将content的编码格式转化为utf-8才能查看。。这里还没弄清楚为什么Expected a bytes object, not a unicode object,先放着。
下面说说写入操作。写入操作之前需要制定encoding的方式为utf-8,另外f.write()时还得先把content的编码格式设置成utf-8,然后再通过decode解码,将utf-8格式解码成Unicode格式,即python内置的编码格式,这样就能正常写入了,而且中文正常显示!!!
下面是最上面代码的输出结果。
-
>>>
-
<class 'str'>
-
{'encoding': 'utf-8', 'confidence': 0.99}
-
[Finished in 2.3s]
先写到这~~~