Python爬虫教程-使用chardet

Spider-03-使用chardet
继续学习python爬虫,我们经常出现解码问题,因为所有的页面编码都不统一,我们使用chardet检测页面的编码,尽可能的减少编码问题的出现

网页编码问题解决
使用chardet 可以自动检测页面文件的编码格式,但是也有可能出错
需要安装chardet,
如果使用Anaconda环境,使用下面命令:
conda install chardet
如果不是,就自己手动在【PyCharm】>【file】>【settings】>【Project Interpreter】>【+】>【chardet】>【install】
具体操作截图:

案例v2

 1 # py03chardet.py
 2 # 使用request下载页面,并自动检测页面编码
 3 
 4 from urllib import request
 5 import chardet
 6 
 7 if __name__ == '__main__':
 8 
 9     url = 'https://jobs.zhaopin.com/CC375882789J00033399409.htm'
10 
11     rsp = request.urlopen(url)
12     # 按住Ctrl键不送,同时点击urlopen,可以查看文档,有函数的具体参数和使用方法
13 
14     html = rsp.read()
15     cs = chardet.detect(html)
16 
17     print("cs的类型:{0}".format(type(cs)))
18     print("监测到的cs数据:{0}".format(cs))
19 
20     html = html.decode(cs.get("encoding", "utf-8"))
21     # 意思是监测到就使用监测到的,监测不到就使用utf-8
22 
23     print("HTML页面为:
%s" % html)

右键运行,截图如下 

编码检测就介绍完了,最要的功能是检测页面的编码,尽可能的减少编码问题的出现

 如果还有问题未能得到解决,搜索887934385交流群,进入后下载资料工具安装包等。最后,感谢观看!

原文地址:https://www.cnblogs.com/pypypy/p/11945465.html