UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc9 in position 167

在用urllib.request库的时候一部小心就会碰到

    url = "http://money.163.com/special/pinglun/"
    data_byte = urllib.request.urlopen(url).read()
    data = data_byte.decode('UTF-8')
    print(data)

报错:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc9 in position 167: invalid continuation byte

这是由于byte字符组没解码好,要加另外一个参数
官方文档中也这么写到

bytearray.decode(encoding=”utf-8”, errors=”strict”)

    Return a string decoded from the given bytes. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.

意思就是字符数组解码成一个utf-8的字符串,可能被设置成不同的处理方案,默认是‘严格’的,有可能抛出UnicodeError,可以改成‘ignore’,’replace’就能解决

我把上面的data_byte.decode(‘UTF-8’)改成data_byte.decode(‘UTF-8’,‘ignore’)就解决了

你可能感兴趣的:(python问题)