2012-07-11 62 views
2

我有一個Python代碼,它嘗試讀取用西裏爾字母(例如俄語)書寫的RSS源。這是我使用的代碼:爲什麼編碼不總是工作?

import feedparser 
from urllib2 import Request, urlopen 

d=feedparser.parse(source_url) 

# Make a loop over the entries of the RSS feed. 
for e in d.entries: 
    # Get the title of the news. 
    title = e.title 
    title = title.replace(' ','%20') 
    title = title.encode('utf-8') 

    # Get the URL of the entry. 
    url = e.link 
    url = url.encode('utf-8') 


    # Make the request. 
    address = 'http://example.org/save_link.php?title=' + title + '&source=' + source_name + '&url=' + url 

    # Submit the link. 
    req = Request(address) 
    f = urlopen(req) 

我用encode('utf-8')由於標題在西裏爾字母給出,它工作正常。 RSS源的一個例子是here。當我嘗試從另一個URL讀取RSS源的列表時出現問題。更詳細地說,有一個網頁,其中包含RSS源的列表(源的URL以及用西里爾文字母給出的名稱)。列表中的一個例子是在這裏:當我嘗試申請編碼(「UTF-8」),該文件中給出的西裏爾字母出現

<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'> 
<html> 
<head> 
<title></title> 
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'> 

ua, Корреспондент, http://k.img.com.ua/rss/ua/news.xml 
ua, Українська Правда, http://www.pravda.com.ua/rss/ 

</body> 
</html> 

的問題。我得到一個UnicodeDecodeError。有人知道爲什麼嗎?

回答

6

encode如果提供它str對象,就會試圖解碼爲unicode只會給UnicodeDecodeError;見http://wiki.python.org/moin/UnicodeDecodeError

您需要的str對象解碼爲unicode第一:

name = name.decode('utf-8') 

這將在UTF-8編碼str,給你一個unicode對象。

它適用於您發佈的代碼,因爲feedparser將已解碼的訂閱源數據返回到unicode

+5

是的,Python 2很有趣。 – 2012-07-11 10:05:50

+0

但是爲什麼'encode'與RSS源的西里爾文標題一起使用,並且它不能與RSS源列表中給出的源的西里爾文名稱一起使用? – Roman 2012-07-11 10:09:22

+0

@Roman可能是因爲你沒有解碼列表中的名字。 – ecatmur 2012-07-11 10:16:52