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()
相关推荐
chenment5 小时前
ComfyUI 自定义节点开发:从零扩展你的图像生成工作流
python·stable diffusion
互联网中的一颗神经元6 小时前
小白python入门 - 25. SQL 与表设计入门
数据库·python·sql
RSTJ_16257 小时前
PYTHON+AI LLM DAY ONE HUNDRED AND EIGHTEEN
python
开源量化GO8 小时前
近期量化学习路径,交易理解和技术实现要接上
人工智能·python
c_lb72888 小时前
近期手工规则量化,学习表达到开发验证要连起来
人工智能·python
tkevinjd8 小时前
MiniCode 项目详解7:Memory 记忆系统
大数据·python·搜索引擎·llm·agent
郭老二9 小时前
【Python】Web框架 FastAPI 详解
python·fastapi
DFT计算杂谈9 小时前
交错磁研究进展材料物性与交叉应用
数据库·人工智能·python·opencv·算法
敖行客 Allthinker9 小时前
docker容器安装Python反推镜像步骤(适用于临时调试用)
python·docker·容器
rrrjqy9 小时前
夏普比率与 Beta——Quant-for-Beginners 量化入门Task7
python·金融