爬虫decode utf-8报错解决办法

UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xa1 in position 160: invalid start byte

问题描述

在爬虫一个小说网站时,在使用urllib获取request的response的时候,要进行解码,相关语句如下:
html = reponse.read().decode(“utf-8”),
该语句写“utf-8”,在执行时会报如下错误:
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xa1 in position 160: invalid start byte

解决问题

将语句:html = reponse.read().decode(“utf-8”)
改为:html = reponse.read().decode(“GBK”)
即:把"utf-8"变为在国标码"GBK"

问题代码如下

def askURL(url):
    head = {
        "User-Agent": "Mozillacko) Chrome6"}
    request = urllib.request.Request(url, headers=head)
    html = ""
    try:
        reponse = urllib.request.urlopen(request)
        //就是下面这句报错!!! 
        //错误原因:decode()里面要放对应的解码格式
        html = reponse.read().decode("utf-8")
        //对我这次爬虫小说的网页来说,下面这句才是对的:
        //html = reponse.read().decode("GBK")
        print("html", html)
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)

问题分析

出现这种问题绝大部分情况是因为文件不是 UTF8 编码的(例如,可能是 GBK 编码的)。解决方法是改为对应的解码方式。

参考链接:

https://www.cnblogs.com/zhangshitong/p/11281312.html
https://blog.csdn.net/qq_37701443/article/details/84964684
https://blog.csdn.net/wang7807564/article/details/78164855/

附上一个网上写的比较好的爬取小说的教程:

爬虫:小说

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值