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

本文介绍了解决使用urllib.request库时遇到的UnicodeDecodeError的方法。通过调整decode()函数中的错误处理参数,可以避免因无效的连续字节而引发的解码错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在用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’)就解决了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值