admin管理员组文章数量:1610857
在对一个网页进行爬取的时候,数据能取下来,最后解析的时候报错:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa4 in position 712: invalid start byte
意思是在进行解析的时候,使用utf8编码格式解析到712个字符的时候出错,去原网页F12,在Console中输入:document.charset,返回结果是GBK,表示该网页的编码格式是GBK,因此Python中应该使用GBK类解析,我这里使用的hyper,默认解析是utf8,我添加了参数,不让hyper帮我解析:
conn = HTTPConnection('www.hkex.hk:443')
conn.request('GET', '/chi/stat/smstat/dayquot/d210219c.htm', None, None)
resp = conn.get_response()
s = resp.read(decode_content=False)
可在响应读取数据处添加decode(encoding='UTF-8', errors='ignore'),解析成utf8,跳过出错的地方:
conn = HTTPConnection('www.hkex.hk:443')
conn.request('GET', '/chi/stat/smstat/dayquot/d210219c.htm', None, None)
resp = conn.get_response()
s = resp.read(decode_content=False).decode(encoding='UTF-8', errors='ignore')
但最好是按照原网页的数据进行解析,即转换为GBK:
conn = HTTPConnection('www.hkex.hk:443')
conn.request('GET', '/chi/stat/smstat/dayquot/d210219c.htm', None, None)
resp = conn.get_response()
s = resp.read(decode_content=False).decode(encoding='GBK', errors='ignore')
本文标签: 报错CodecDecodePythonUnicodeDecodeError
版权声明:本文标题:Python报错:UnicodeDecodeError: ‘utf8‘ codec can‘t decode byte 0xa4 in position 712: invalid start byte 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1728606341a1165504.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论