python 爬虫问题解决

在爬取晋江网站时遇到了UnicodeDecodeError,原因是网站响应使用了gzip压缩。通过设置headers的'Accept-Encoding'为'gzip'并使用gzip库解压网页内容解决了该问题。同时,针对不同编码,使用`f.read().decode("gbk","ignore")`避免解码错误。最后,统一设置请求头以gzip格式发送,成功爬取了小说的名称、作者、字数和链接,并进一步爬取了小说文案,但还需改进文案中字符的处理方式。" 112086130,10295034,Java环境配置与 HelloWorld 程序,"['JAVA', '编程基础', '软件安装', '开发环境']
摘要由CSDN通过智能技术生成

1、爬取晋江网页

(1)报错:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start by...

(2)原因:网站发包是gzip格式,因此解码会是乱码:headers['Accept-Encoding'] = "gzip

(3)解决

用gzip包解压传回来的网页

正常

def askURL(url):
    head = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 Edg/87.0.664.75"
    }

    request = urllib.request.Request(url, headers=head)
    html = ""
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode('GBK')
        # html = response.read()
        # buff = BytesIO(html)
        # f = gzip.GzipFile(fileobj=buff)
        # html = f.read().decode("GBK")
        # 这是之前解不开编码时尝试的其它方法
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
    return html

gzip:

import gzip

from io import BytesIO

def askURL_novel(url):
    head = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 Edg/87.0.664.75",
        "Accept-encoding": "gzip"
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值