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()
相关推荐
小嘉丶学长9 小时前
Day13 · 列表与元组
linux·运维·服务器·开发语言·python
小小张说故事9 小时前
Python 的 int 为什么不会溢出?拆开 PyLongObject 和它背后那串变长数组
python
威哥爱编程9 小时前
Python 智能体开发实战 03:聊十轮就“失忆”,账单还翻倍?管好上下文,Token 立省一半
python·agent
情 九9 小时前
MCP 开发环境搭建:Mac 与 Windows 跑通 Python 服务和 stdio 客户端
windows·python·macos·mcp
SEO_juper9 小时前
Bash 交叉验证 robots.txt 和 sitemap:两个文件自相矛盾,页面永远收录不了
开发语言·python·node.js·json·bash
日日大王学编程10 小时前
LangGraph 基本用法详解:从入门到实战
python·语言模型·langchain
威哥爱编程10 小时前
Python 智能体开发实战 04:模型答得挺漂亮,程序却读不懂?让回答直接变成能入库的 JSON
python·agent
全栈陈序员10 小时前
【Python】基础语法入门(三十)—— Web 开发入门:用 Flask 搭建第一个网站
前端·python·flask
全栈陈序员10 小时前
【Python】基础语法入门(三十三)—— 日志系统详解:用 logging 记录程序运行
java·开发语言·python
晗夜未央10 小时前
跨仓库 Skill 换台电脑就失效?用 Git remote 校验项目
人工智能·git·python