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()
相关推荐
言乐610 小时前
Python根据关联词搜索模型
开发语言·人工智能·python·机器学习·django
泡海椒13 小时前
JQuick-Excel FORMAT 导出格式实战:日期、金额显示与 TRANSFORM 的边界
前端·python·excel
承渊政道14 小时前
星空组网+Python实战:在另一台电脑上查看CSV报表
运维·开发语言·python·csv·星空组网
LOVE️YOU18 小时前
Python 中 Tuple 为什么有时可 Hash,有时不可 Hash?
开发语言·python·哈希算法
小oo呆19 小时前
【学习心得】迭代器和可迭代对象
开发语言·python
AC赳赳老秦19 小时前
采集行为合规自检:OpenClaw 自动校验 robots 协议与采集频率,规避违规采集风险
java·开发语言·c++·python·php·deepseek·openclaw
迅猛龙办公室19 小时前
Python输出当前计算机的系统日期和时间
开发语言·前端·python
XiaoMaqqqq21 小时前
知名的IP驱动产业新场景新工具
网络·python·网络协议·tcp/ip
言乐621 小时前
Python实现语音审核模型
开发语言·python·django·virtualenv·pygame
程序员清风1 天前
Python 数据分析环境搭建:从 Jupyter 到 pandas
python·jupyter·数据分析