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()
相关推荐
2301_809204702 分钟前
Golang如何做Clean Architecture_Golang整洁架构教程【详解】
jvm·数据库·python
m0_624578592 分钟前
PHP源码能否在无盘工作站运行_网络启动硬件要求【说明】
jvm·数据库·python
战南诚3 分钟前
Flask中的URL ——url_for() 与 自定义动态路由过滤器
后端·python·flask
yexuhgu4 分钟前
CSS Grid布局如何实现项目重叠效果_利用z-index与grid-area实现
jvm·数据库·python
源码之家8 分钟前
计算机毕业设计:Python基于知识图谱的医疗问答系统 Neo4j 机器学习 BERT 深度学习 ECharts(建议收藏)✅
python·深度学习·机器学习·信息可视化·数据分析·知识图谱·课程设计
m0_5967490910 分钟前
SQL统计分组内的所有数据唯一值_使用DISTINCT汇总
jvm·数据库·python
WL_Aurora11 分钟前
备战蓝桥杯国赛【Day 11】
python·蓝桥杯
m0_6091604912 分钟前
Golang项目目录结构如何组织_Golang项目结构教程【核心】
jvm·数据库·python
Dust-Chasing15 分钟前
Claude Code源码剖析 - Phase1
人工智能·python·ai
m0_4636722015 分钟前
如何优雅处理SQL存储过程异常_使用TRY-CATCH块机制
jvm·数据库·python