2012-07-11 5 views
2

키릴 문자로 작성된 RSS 소스 (예 : 러시아어)를 읽는 데 필요한 Python 코드가 있습니다. 이것은 내가 사용하는 코드입니다 : 제목이 키릴 문자로 제공되기 때문에인코딩이 항상 작동하지 않는 이유는 무엇입니까?

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

encodestr 개체를 제공하면 unicode으로 디코딩하려고 시도하지만이 경우에만 UnicodeDecodeError을 제공합니다. http://wiki.python.org/moin/UnicodeDecodeError을 참조하십시오.

는 먼저 unicodestr 객체를 해독해야합니다

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

이 UTF-8 인코딩에서 str을 당신에게 unicode 객체를 제공 할 것입니다.

feedparser은 이미 디코딩 된 피드 데이터를 unicode으로 반환하기 때문에 게시 한 코드에서 작동합니다.

+5

예, Python 2는 재미 있습니다. –

+0

그러나 왜'encode'는 RSS 소스의 키릴 문자로 작동하며 RSS 소스 목록에 제공된 소스의 키릴 문자 이름으로는 작동하지 않습니까? – Roman

+0

@Roman 아마도 당신이 목록에서 이름을 해독하지 않았기 때문입니다. – ecatmur

관련 문제