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 源的一个示例。当我尝试从另一个 URL 读取 RSS 源列表时出现问题。更详细地说,有一个网页包含 RSS 源列表(源的 URL 以及以西里尔字母给出的名称)。列表示例如下:

<!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>

当我尝试将 encode('utf-8') 应用于本文档中给出的西里尔字母时,就会出现问题。我得到一个UnicodeDecodeError. 有人知道为什么吗?

4

1 回答 1

6

encodeUnicodeDecodeError当您向它提供一个str对象,然后它会尝试解码为它时才会给出unicode;见http://wiki.python.org/moin/UnicodeDecodeError

您需要先将str对象解码为unicode

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

这将采用strUTF-8 编码并为您提供一个unicode对象。

它适用于您发布的代码,因为feedparser返回的提要数据已经解码为unicode.

于 2012-07-11T10:03:17.747 回答