美文网首页
BeautifulSoup爬取网页过程中会出现乱码

BeautifulSoup爬取网页过程中会出现乱码

作者: 五月笑忘 | 来源:发表于2021-01-26 13:34 被阅读0次

    问题描述

    在尝试爬取小说时,发现爬取到的正文格式是正确的,但是章节列表会出现乱码,经过仔细搜索终于解决,特此记录


    运行时可以看到,文字都是乱码

    源代码

          req = requests.get(url=self.target)
          bf = BeautifulSoup(req.text, 'html.parser')
          div = bf.findAll('div', class_='listmain')
          a_bf = BeautifulSoup(str(div[0]), "html.parser")
          a = a_bf.findAll('a')
          print(a[0].)
    

    解决方案

    1. 确定当前网页的编码格式,可以在控制台中查看,在console中输入
    document.charset
    

    下图可以看出,该网页是采用GBK编码


    控制台输出结果,GBK
    1. 添加代码,将编码格式设置为对应的编码格式
     req = requests.get(url=self.target)
     req.encoding = 'GBK' //将编码格式设置为网页对应的格式,在这里就是GBK
     bf = BeautifulSoup(req.text, 'html.parser')
    
    1. 问题解决


      增加代码后,文字显示正确

    相关文章

      网友评论

          本文标题:BeautifulSoup爬取网页过程中会出现乱码

          本文链接:https://www.haomeiwen.com/subject/nllgzktx.html