我一直在修改以下脚本:
# -*- coding: utf8 -*-
import codecs
from BeautifulSoup import BeautifulSoup, NavigableString,
UnicodeDammit
import urllib2,sys
import time
try:
import timeoutsocket # http://www.timo-tasi.org/python/timeoutsocket.py
timeoutsocket.setDefaultSocketTimeout(10)
except ImportError:
pass
h=u'\u3000\u3000\u4fe1\u606f\u901a\u4fe1\u6280\u672f'
address=urllib2.urlopen('http://stock.eastmoney.com/news/1408,20101022101395594.html').read()
soup=BeautifulSoup(address)
p=soup.findAll('p')
t=p[2].string[:10]
输出如下:
print t
四、
print h
信息通
t
u'\xa1\xa1\xa1\xa1\xd0\xc5\xcf\xa2\xcd\xa8'
h
u'\u3000\u3000\u4fe1\u606f\u901a'
h.encode('gbk')
'\xa1\xa1\xa1\xa1\xd0\xc5\xcf\xa2\xcd\xa8'
简单地说:当我通过beauthulsoup传入这个html时,需要 gbk对文本进行编码,认为它是unicode,无法识别 需要先解码。”但是,h和t应该是一样的, 因为h就是我从html文件中获取文本并转换它 手动操作。在
我怎么解决这个问题?在
最佳
惠顿
该文件的meta标记声明字符集是GB2312,但数据中包含一个来自新的GBK/GB18030的字符,这就是导致beautifulGroup失败的原因:
此时,UnicodeDammit退出,尝试chardet,UTF-8,最后Windows-1252,这总是成功的——从外观上看,这就是你得到的。在
如果我们告诉解码器用“?”替换未识别的字符,我们可以看到GB2312中缺少的字符:
^{pr2}$使用正确的编码:
同时:
相关问题 更多 >
编程相关推荐