开发者社区> 问答> 正文

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 579 0
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
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载