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_764441338 分钟前
新能源汽车电磁辐射高级预测
python·算法·数学建模·汽车
q***37515 分钟前
爬虫学习 01 Web Scraper的使用
前端·爬虫·学习
爱吃泡芙的小白白18 分钟前
使用某云超算平台Jupyterlab的使用方法(自用)
运维·服务器·python·学习记录
qq_2037694919 分钟前
在conda环境中使用jupyter
python·jupyter·conda
二川bro1 小时前
Python模型优化实战:深度学习加速与压缩技巧
python
l***74942 小时前
SQL Server2022版+SSMS安装教程(保姆级)
后端·python·flask
傻啦嘿哟2 小时前
Python实现PDF文档高效转换为HTML文件:从基础到进阶的完整指南
python·pdf·html
天下无敌笨笨熊3 小时前
ES作为向量库研究
大数据·python·elasticsearch
数据知道3 小时前
FastAPI项目:从零到一搭建一个网站导航系统
python·mysql·fastapi·python web·python项目
程序员爱钓鱼4 小时前
Python 编程实战 · 进阶与职业发展:数据分析与 AI(Pandas、NumPy、Scikit-learn)
后端·python·trae