weixin_55061897 2022-01-08 21:33 采纳率: 60%
浏览 53
已结题

pychon中爬取网页信息,输出时乱码问题,求解决

今天练习一下pychon的爬取,就写了一个爬取三国演义的爬虫,结果在输出中文时出现乱码。

import requests
from bs4 import  BeautifulSoup
url='https://www.shicimingju.com/book/sanguoyanyi.html'
headers={
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
}
page_text=requests.get(url=url,headers=headers).text
soup=BeautifulSoup(page_text,'lxml')
li_list=soup.select('.book-mulu>ul>li')
fp=open('./三国演义.txt','w',encoding='utf-8')
for li in li_list:
    title=li.a.string
    detail_url='https://www.shicimingju.com/'+li.a['href']
    detail_url_text=requests.get(url=detail_url,headers=headers).text
    detail_soup=BeautifulSoup(detail_url_text,'lxml')
    div_tag=detail_soup.find('div',class_='chapter_content')
    content = div_tag.text
    fp.write(title+':'+content+'\n')
    print(title,'爬取完毕!!!')
print('全部爬取完毕')

爬出来的全是中文乱码:

img


已经加入了encoding='utf-8'后依然如此,上网找百度也寻觅无果,求指点

  • 写回答

1条回答 默认 最新

  • 关注

    你requests 读取页面文件的编码不对 ,用 res.encoding='utf-8'或res.encoding='gbk'设置下读取页面文件用的编码, 再获取res.text即可,比如

    res=requests.get('http://www.xxxx.com')
    res.encoding='utf-8'
    #或res.encoding='gbk'
    print(res.text)
    

    或者也可以设置 res.encoding=res.apparent_encoding 自动从网页的内容中分析网页编码

    你题目的解答代码如下:

    import requests
    from bs4 import  BeautifulSoup
    url='https://www.shicimingju.com/book/sanguoyanyi.html'
    headers={
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
    }
    
    res=requests.get(url=url,headers=headers)
    res.encoding=res.apparent_encoding
    page_text=res.text
    
    soup=BeautifulSoup(page_text,'lxml')
    li_list=soup.select('.book-mulu>ul>li')
    fp=open('./三国演义.txt','w',encoding='utf-8')
    for li in li_list:
        title=li.a.string
        detail_url='https://www.shicimingju.com/'+li.a['href']
        detail_url_text=requests.get(url=detail_url,headers=headers).text
        detail_soup=BeautifulSoup(detail_url_text,'lxml')
        div_tag=detail_soup.find('div',class_='chapter_content')
        content = div_tag.text
        fp.write(title+':'+content+'\n')
        print(title,'爬取完毕!!!')
    print('全部爬取完毕')
    

    如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 1月16日
  • 已采纳回答 1月8日
  • 创建了问题 1月8日

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效