【python】获得字符串编码方式

深度链接 / 2023-12-06 21:48:31 / 203

爬取页面时需要解码,在抓取页面未体现其编码方式时,如何获取页面的编码方式呢?

1、通常我们获取爬取页面编码方式是通过查看爬取页面的源文件,有时通过此方法可能无法识别页面编码方式

如:查看www.sdlj.ltd页面编码方式

wrx.jpg360反馈意见截图16510930294016.png

2、使用chardet.detect检测编码类型

#安装chardet,如何使用pip命令,请查看扩展阅读
[root@wrx python3]# pip3 install chardet
#查看安装信息
[root@wrx python3]# pip3 show --files chardet
Name: chardet
Version: 3.0.4
Summary: Universal encoding detector for Python 2 and 3
Home-page: https://github.com/chardet/chardet
Author: Daniel Blanchard
Author-email: dan.blanchard@gmail.com
License: LGPL
Location: /usr/local/lib/python3.4/site-packages
Requires: 
Files:
  ../../../bin/chardetect
#已经安装chardet后使用chardet.detect(str)检测
……
request = urllib.request.Request(url,headers=headers)	
response = urllib.request.urlopen(request)
res = response.read()
print(chardet.detect(res))
输出结果
{'language': 'Chinese', 'confidence': 0.99, 'encoding': 'GB2312'}