Python爬取诗词名句网中三国演义的乱码问题

一、乱码问题

为解决中文乱码问题,可使用chardet.detect()检测文本编码格式

详细:

Python爬虫解决中文乱码_脑子不好真君的博客-CSDN博客

二、代码

python 复制代码
#爬取三国演义
import requests
import chardet
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/117.0.0.0 Safari/537.36 Edg/117.0.2045.47'
}

resp=requests.get(url=url,headers=headers)
encoding=chardet.detect(resp.content)["encoding"]
#print(encoding)
resp.encoding=encoding
page_text=resp.text
#print(page_text)

soup=BeautifulSoup(page_text,'lxml')
li_list=soup.select('.book-mulu > ul > li')
#print(li_list)
fp=open('D:\\Programming\\Microsoft VS Code Data\\WebCrawler\\data\\sanguo\\sanguo.txt',
        'a+',
        encoding=encoding,
        )
for li in li_list:
    title=li.a.string
    zhangjie_url='https://www.shicimingju.com'+li.a['href']
    zhangjie_page=requests.get(url=zhangjie_url,headers=headers)
    encoding=chardet.detect(zhangjie_page.content)['encoding']
    zhangjie_page.encoding=encoding
    #print(encoding)
    zhangjie_page_text=zhangjie_page.text

    zhangjie_soup=BeautifulSoup(zhangjie_page_text,'lxml')
    div_content=zhangjie_soup.find('div',class_='chapter_content')
    content=div_content.text
    fp.write(title+'\n'+content+'\n')
    print(title,'爬取成功!')
fp.close()
相关推荐
databook6 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室7 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三8 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271112 小时前
Python之语言特点
python
刘立军12 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机15 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机16 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i18 小时前
django中的FBV 和 CBV
python·django
c8i18 小时前
python中的闭包和装饰器
python
这里有鱼汤21 小时前
小白必看:QMT里的miniQMT入门教程
后端·python