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()
相关推荐
TsengOnce3 分钟前
阿里云ECS多版本JDK切换
java·python·阿里云
Hi_kenyon4 分钟前
FastAPI+VUE3创建一个项目的步骤模板(三)
python·fastapi
Flyora18 分钟前
【踩坑实录】PyInstaller 打包 “找不到库的完整解决方案
python
测试老哥18 分钟前
2026软件测试面试大全(含答案+文档)
自动化测试·软件测试·python·测试工具·面试·职场和发展·测试用例
yaoh.wang25 分钟前
力扣(LeetCode) 28: 找出字符串中第一个匹配项的下标 - 解法思
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
手揽回忆怎么睡29 分钟前
win11灵活控制Python版本,使用pyenv-win
开发语言·python
唯唯qwe-30 分钟前
Day20:贪心算法,跳跃游戏
python·算法·贪心算法
@淡 定31 分钟前
动态代理(JDK动态代理/CGLIB动态代理
java·开发语言·python
破烂pan33 分钟前
Python 整合 Redis 哨兵(Sentinel)与集群(Cluster)实战指南
redis·python·sentinel
程序员杰哥40 分钟前
接口测试之文件上传
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试