2011-07-19 122 views
2

这是我的脚本蟒蛇UTF-8的问题

# -*- coding: utf-8 -*- 
from BeautifulSoup import BeautifulSoup 
import urllib2 

res = urllib2.urlopen('http://tazeh.net') 
html = res.read() 

soup = BeautifulSoup(''.join(html)) 

title = soup.findAll('title') 
print title 

时,即时通讯正在运行在终端这个剧本我得到委屈一样,

$ python test.py 

[<title>ٞاŰ&OElig;گاŮ&Dagger; ؎بعŰ&OElig; ŘŞŘ­Ů&bdquo;Ű&OElig;Ů&bdquo;Ű&OElig; تازŮ&Dagger;</title>] 

这个标题文本在UTF-8编码和波斯语

我是新来的python有什么不对吗?

+0

你有没有尝试过title.decode()? – Daniel

+0

将脚本底部改为'code' title = soup.findAll('title') title = title [0] .string.decode('utf-8') print title'code' got error return codecs.utf_8_decode(输入,错误,True) UnicodeEncodeError:'ascii'编解码器无法编码位置0-4的字符:序号不在范围内(128) –

+0

您的问题解决了吗? :D – Efazati

回答

3

如果我添加(如一个评论中用处不大的地方提示做):

html = html[:10000].decode("utf-8") 

(切片是因为解码失败在进一步偏移到页面)

前:

soup = BeautifulSoup(html) 

它打印:

[<title>پایگاه خبری تحلیلی تازه</title>] 
+0

谢谢,但为什么使用html [:10000]? –

+0

切片[:10000]是因为解码在进一步进入页面的偏移处失败。 –

1

''.join(html)是没有必要的。变量html已经是单个字符串。

但是,看起来页面没有正确编码为UTF-8。