[問題] BeautifulSoup 指定title變亂碼

作者: etime (suck)   2014-06-01 21:17:38
os: win7
python version: python 2.7
IDE: PyScripter
我在抓網站資料的時候,第一次抓,全都是亂碼,無論是.prettify()或是.title。
後來發現是編碼的問題,用chardet去做確認來源是big5,
在塞進BeautifulSoup會被轉成windows-1252
usock = urllib2.urlopen(url)
data = usock.read()
usock.close()
bdata = BeautifulSoup(data)
print bdata.prettify()
print chardet.detect(data)
print type(data)
print bdata.original_encoding
print bdata.title
{'confidence': 0.99, 'encoding': 'Big5'}
<type 'str'>
windows-1252
接著強制轉為utf-8
usock = urllib2.urlopen(url)
data = usock.read()
changecode = unicode(data, 'big5','ignore').encode('utf-8','ignore')
usock.close()
bdata = BeautifulSoup(changecode)
print bdata.prettify()
print chardet.detect(changecode)
print type(changecode)
print bdata.original_encoding
print bdata.title
{'confidence': 0.99, 'encoding': 'utf-8'}
<type 'str'>
utf-8
這次有個奇怪的地方,在使用.prettify()輸出整個網站資料時顯示是正常的
但改用.title卻是亂碼?除非把bdata.title改成bdata.title.encode('big5')
就能正常的文字...請問這狀況應該是那裡有問題?

Links booklink

Contact Us: admin [ a t ] ucptt.com