加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python处理中文编码和判断编码示例

发布时间:2020-05-24 08:27:14 所属栏目:Python 来源:互联网
导读:下面所说的都是针对python2.7复制代码代码如下:#coding:utf-8#chardet需要下载安装importchardet#抓取网页htmlline="http://www.***.com"html_1=urllib2.urlopen(line,timeout=120).read()#printhtml_1encoding_

下面所说的都是针对python2.7

复制代码 代码如下:
#coding:utf-8
#chardet 需要下载安装

import chardet
#抓取网页html
line = "http://www.***.com"
html_1 = urllib2.urlopen(line,timeout=120).read()
#print html_1
encoding_dict = chardet.detect(html_1)
#print encoding
web_encoding = encoding_dict['encoding']
if web_encoding == 'utf-8' or web_encoding == 'UTF-8':

  html = html_1
else :
   html = html_1.decode('gbk','ignore').encode('utf-8')

#有以上处理,整个html就不会是乱码。

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读