Python爬虫解决中文乱码

目录

一、中文乱码

二、chardet.detect()解决

三、在页面查找编码格式解决


一、中文乱码

问题在于文本的编码格式不正确

python 复制代码
import requests

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).text
print(resp)

二、chardet.detect()解决

第一步:

在终端输入pip install chardet安装chardet库

pip install chardet

第二步:

import chardet

第三步:

chardet库提供了detect函数,用于检测给定文本的编码格式

encoding=chardet.detect(resp.content)"encoding"

resp.encoding=encoding

python 复制代码
import requests
import chardet

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()函数返回的字典中的"encoding"键对应的值 该值表示检测到的编码格式
encoding=chardet.detect(resp.content)["encoding"]
#print(encoding)
resp.encoding=encoding

page_text=resp.text
#print(page_text)

三、在页面查找编码格式解决

或者在页面Ctrl+U,再Ctrl+F,输入charset查找文本编码格式

相关推荐
诺伦12 小时前
从一键分发到 AI 自动运营:内容矩阵工具三代技术架构拆解 | RiseClaw玄策
python·agent·架构设计·增长运营·ai自动运营·内容营销自动化
有同事要进步12 小时前
LeetCode 14. 最长公共前缀:纵向扫描一次讲透
开发语言·python
XiaoMaqqqq12 小时前
目前正规的IP驱动产业新场景新工具哪个好
网络·python·网络协议·tcp/ip
cui_ruicheng12 小时前
FastAPI 应用开发(五)——SQLAlchemy ORM、APIRouter 与 Alembic 数据库迁移
python·fastapi·web
silvamux_12 小时前
豆包 API 调用教程:Python 接入可跑通示例
开发语言·python
卿卿的产品经理日记12 小时前
【AI产品经理实战】Day 37|拆开 JSON 与 EXE:数据都有格式
人工智能·笔记·python·json·产品经理
棉猴13 小时前
玩游戏学Python10-算术运算符应用2
开发语言·python·玩游戏·游戏编程
deepseek2313 小时前
Dependabot匿名私有仓库开放后仍更新失败?组织级镜像的访问边界与排查实战
python·github·devops·软件供应链·dependabot
曲径海盗13 小时前
【Python 学习第 28 天】字符串基础
python·学习笔记·编程入门
for_ever_love__13 小时前
LangChain 模型参数调优:temperature、max_tokens 这些到底怎么设
python·语言模型·langchain·aigc·模型参数·temperature·max_tokens