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()
相关推荐
c_lb72887 分钟前
期货主连研究具体月实盘:KQ 连续与标的月份偏差怎么记
python·区块链
绘梨衣5478 分钟前
采集基类设计遇到的描述符bug
爬虫·python·bug
TechWayfarer18 分钟前
IP精准定位服务在保险行业的接入实践:区域需求洞察与精准服务
数据库·python·tcp/ip·flask
Li#1 小时前
AI编写操作使用说明书需要用到的工具和能力
python·ai编程·ai写作
红宝村村长1 小时前
torch.autograd.Function.apply()
开发语言·python
花间相见1 小时前
【LeetCode01】—— 无重复字符的最长子串:滑动窗口经典题详解
python·算法·leetcode
何以解忧,唯有..1 小时前
Python 中的继承机制:从基础到高级用法详解
java·开发语言·python
try2find1 小时前
agent环境安装spacy
python·智能体
ellenwan20262 小时前
期货程序化开平标志错了总拒单:天勤 last_msg 排查思路
python
装不满的克莱因瓶2 小时前
自动微分的原理:计算图与前向传播
人工智能·pytorch·python·数学·ai·微积分·计算图