VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > python教程 >
  • python基础教程之python处理抓取中文编码和判断编码

本站最新发布   Python从入门到精通|Python基础教程
试听地址  
https://www.xin3721.com/eschool/pythonxin3721/


在开发自用爬虫过程中,有的网页是utf-8,有的是gb2312,有的是gbk,如果不加处理,采集到的都是乱码,解决的方法是将html处理成统一的utf-8编码

版本python2.7

1
2
3
4
5
6
7
8
9
10
11
12
13
#coding:utf-8
import chardet
#抓取网页html
line = "http://www.pythontab.com"
html_1 = urllib2.urlopen(line,timeout=120).read()
encoding_dict = chardet.detect(html_1)
print encoding
web_encoding = encoding_dict['encoding']
#处理,整个html就不会是乱码。
if web_encoding == 'utf-8' or web_encoding == 'UTF-8':
html = html_1
else :
html = html_1.decode('gbk','ignore').encode('utf-8')

相关教程