开发者社区 问答 正文

python爬取页面的时候如何过滤非GBK编码的不读取??报错

就是我要爬一个页面的数据,这个页面是GBK的,但是里面会有人回复非GBK的帖子,比如傘€傘€傘€傘€ ”,这样爬出来的字符如果要decode('gbk')的时候会报错

>>> new.decode('gbk')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 1875: illegal multibyte sequence
那怎么样才能过滤掉这些非GBK的字符呢??

展开
收起
爱吃鱼的程序员 2020-06-22 17:50:19 599 分享
分享
版权
举报
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    decode('gbk','ignore')这个非常好使谢谢加上异常捕获,但是写个函数通吃大部分编码会更好一些

    是这样的吗?

    <preclass="brush:python;toolbar:true;auto-links:false;">defmdcode(str,encoding='utf-8'):ifisinstance(str,unicode):returnstr.encode(encoding)forcin('utf-8','gb18030','gbk','gb2312','utf-16'):try:ifencoding=='unicode':returnstr.decode(c)else:returnstr.decode(c).encode(encoding)except:passraise'Unknowncharset'

    这个霸气啊~~

    2020-06-22 17:50:36 举报
    赞同 评论

    评论

    全部评论 (0)

    登录后可评论
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等