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

WBOY
Release: 2016-06-16 08:45:04
Original
1037 people have browsed it

下面所说的都是针对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就不会是乱码。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!