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查找文本编码格式

相关推荐
大写-凌祁8 分钟前
论文阅读:HySCDG生成式数据处理流程
论文阅读·人工智能·笔记·python·机器学习
爱喝喜茶爱吃烤冷面的小黑黑32 分钟前
小黑一层层削苹果皮式大模型应用探索:langchain中智能体思考和执行工具的demo
python·langchain·代理模式
Blossom.1182 小时前
使用Python和Flask构建简单的机器学习API
人工智能·python·深度学习·目标检测·机器学习·数据挖掘·flask
Love__Tay2 小时前
【学习笔记】Python金融基础
开发语言·笔记·python·学习·金融
有风南来3 小时前
算术图片验证码(四则运算)+selenium
自动化测试·python·selenium·算术图片验证码·四则运算验证码·加减乘除图片验证码
wangjinjin1803 小时前
Python Excel 文件处理:openpyxl 与 pandas 库完全指南
开发语言·python
Yxh181377845544 小时前
抖去推--短视频矩阵系统源码开发
人工智能·python·矩阵
Humbunklung4 小时前
PySide6 GUI 学习笔记——常用类及控件使用方法(多行文本控件QTextEdit)
笔记·python·学习·pyqt
火车叼位5 小时前
使用 uv 工具在 Windows 系统快速下载安装与切换 Python
python
心扬5 小时前
python网络编程
开发语言·网络·python·tcp/ip