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()
相关推荐
apcipot_rain16 分钟前
Python实战——蒙特卡洛模拟分析杀牌游戏技能收益
python·游戏·数学建模
老绿光20 分钟前
Python 字典完全指南:从入门到实战
linux·服务器·python
是小蟹呀^31 分钟前
【总结】LangChain中如何维持记忆
python·langchain·memory
蓝色的杯子32 分钟前
OpenClaw一文详细了解-手搓OpenClaw-4 Tool Runtime
人工智能·python
克里普crirp39 分钟前
电离层TEC地图中添加晨昏线/昼夜转换线
python
Dxy123931021640 分钟前
Python使用PyEnchant详解:打造高效拼写检查工具
开发语言·python
架构师老Y1 小时前
011、消息队列应用:RabbitMQ、Kafka与Celery
python·架构·kafka·rabbitmq·ruby
枫叶林FYL1 小时前
【Python高级工程与架构实战】项目四:生产级LLM Agent框架:基于PydanticAI的类型安全企业级实现
人工智能·python·自然语言处理
龙腾AI白云1 小时前
多模大模型应用实战:智能问答系统开发
python·机器学习·数据分析·django·tornado
Hommy881 小时前
【开源剪映小助手】配置与部署
python·开源·aigc·剪映小助手