2009-01-20 45 views
4

使用BeautifulSoup 3.1.0.1和Python 2.5.2,並嘗試使用法語解析網頁。然而,當我打電話的findAll,我得到以下錯誤:使用BeautifulSoup 3.1.0.1和Python 2.5.2的UnicodeEncodeError

UnicodeEncodeError: 'ASCII' 編解碼器不能編碼字符U '\ xe9' 在1146的位置是:序數不在範圍內(128)

下面是代碼我目前正在運行:

import urllib2 
from BeautifulSoup import BeautifulSoup 
page = urllib2.urlopen("http://fr.encarta.msn.com/encyclopedia_761561798/Paris.html") 
soup = BeautifulSoup(page, fromEncoding="latin1") 
r = soup.findAll("table") 
print r 

沒有任何人有一個想法,爲什麼?

謝謝!

UPDATE:作爲resquested,以下是完整回溯

Traceback (most recent call last): 
    File "[...]\test.py", line 6, in <module> 
    print r 
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1146-1147: ordinal not in range(128) 

回答

11

這是另一種思路。您的終端無法顯示來自Python的unicode字符串。解釋器首先嚐試將其轉換爲ASCII。打印前您應該明確地對其進行編碼。我不知道soup.findAll()的確切語義。但它可能類似於:

for t in soup.findAll("table"): 
    print t.encode('latin1') 

如果t確實是一個字符串。也許它只是您需要構建要顯示的數據的另一個對象。

+1

它的工作原理! :D但是,您的意思是「您的終端無法顯示來自Python的unicode字符串」。我在IDLE(Python Shell)中運行我的腳本。這應該工作,不是嗎? – Martin 2009-01-20 22:28:01