这个问题到python3里面就没了,python3 似乎将这个无形中解决了。
错误信息:
utf8 codec can't decode byte 0xb5 in position有汉字
抓取网页的时候,网页可能有两种编码(utf-8 + GBK23)
编码有中文 也有英文
html的编码是ANSI的,另存为UTF-8即可。
错误信息
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 108: ordinal not in range(128)
混淆了 python2 里边的 str 和 unicode 数据类型。
0.
你需要的是让编码用实际编码而不是 ascii
1.
对需要 str->unicode 的代码,可以在前边写上
import sys
reload(sys)
sys.setdefaultencoding('utf8')
把 str 编码由 ascii 改为 utf8 (或 gb18030)
2.
python3 区分了 unicode str 和 byte arrary,并且默认编码不再是 ascii
You use u"你好".encode('utf8') to encode an unicode string. But if you want to represent "你好", you should decode it. Just like:
"你好".decode("utf8")
encode converts a unicode object to a string object. But here you have invoked it on a string object (because you don't have the u). So python has to convert the string to a unicode object first. So it does the equivalent of"你好".decode().encode('utf-8')