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

相关推荐
智航GIS18 分钟前
2.3 运算符详解
开发语言·python
屋顶那猫18 分钟前
使用pyinstaller打包pytest项目
python·pytest
web3.088899922 分钟前
接入API-自动化批量获取淘宝商品详情数据
开发语言·python
刹那间的回眸x.y28 分钟前
UnitTestReport挺好用
python
码农水水1 小时前
腾讯Java面试被问:阻塞队列BlockingQueue的实现原理
java·后端·python·面试
曲幽1 小时前
Flask登录验证实战:从零构建一个基础的账号密码登录系统
python·flask·web·session·username·login
superman超哥1 小时前
仓颉类型别名的使用方法深度解析
c语言·开发语言·c++·python·仓颉
卡尔特斯1 小时前
pyenv 安装的 python 版本缺少 tkinter 报错 import _tkinter # If this fails your Python xxx
python
3824278271 小时前
python :__call__方法
开发语言·python
八月ouc1 小时前
Python实战小游戏(三): 简易文件管理器
python·shutil·文件管理器·os.walk·pathlib