2011-03-20 6 views
2

PyRSS2Gen을 사용하고 있으며 피드의 각 항목에 원시 HTML (특히 이미지 몇 장)을 게시하고 싶습니다.파이썬 생성 RSS : 원시 HTML 출력?

그러나 RSSItem의 생성자가 '이미지'를 허용하지 않으며 모든 HTML이 자동 이스케이프 처리 된 것처럼 보입니다.이 모든 것을 영원히 얻을 수있는 영리한 방법이 있습니까?

찾았지만 this post 코드 예제가 작동하지 않는 것 같습니다.

누군가가 더 나은 해결책을 가지고 있다면 PyRSS2Gen에 연결되지 않습니다. 아마 나는 내 자신의 RSS 피드를 작성해야합니까?

감사합니다.

답변

3

나는 고통스런 경험을 통해 PyRSS2Gen이 이것을위한 방법이 아니라는 것을 알게되었습니다. 문제는 PyRSS2Gen이 Python의 sax 라이브러리, 특히 saxutility.xmlwriter를 사용한다는 것입니다. saxutility.xmlwriter는 꺾쇠 괄호를 포함하여 XML로 이스케이프해야하는 모든 문자를 이스케이프 처리합니다. 따라서 PyRSS2Gen을 확장하여 태그를 추가하더라도 문제는 여전히 남아 있습니다.

일반적으로 RSS (HTML이 아닌 XML)의 HTML은 CDATA 섹션으로 싸여 있습니다. Python의 sax 라이브러리에는 CDATA 개념이 없지만 minidom은 않습니다. 그래서 제가 한 것은 PyRSS2Gen을 삭제하고, 코드를 추가하고, minidom을 사용하여 XML을 생성하는 것입니다.

당신은 당신이 좋아하는 문서를 구축 minidom에서

(xml.dom.minidom 가져 오기 문서에서) 문서를 필요는 XML (RSS)를 생성 한 후 등

doc = Document() 
rss=doc.createElement('rss') 
rss.setAttribute('version', '2.0') 
doc.appendChild(rss) 
channel=doc.createElement('channel') 
rss.appendChild(channel) 
channelTitle=doc.createElement('title') 
channel.appendChild(channelTitle) 

때, 그리고 파일 당신은 완료 :

f = open('whitegrass.xml', "w") 
doc.writexml(f) 
f.close() 
+1

당신의 대답은 [RSS2Producer] 쓰기 나에게 영감을 https://github.com/nathan-osman/rss2producer),'xml.dom.minidom'을 사용하여 RSS 2.0 피드를 생성합니다. 이 패키지는'pip install rss2producer'로 설치할 수 있습니다. –

+0

Nathan, 멋지다! 나는 그것을 조사해야 할 것이다. – ViennaMike

2

난 당신이 나와있는 블로그 게시물을 작성한 사람이었다. 요지에서 코드를 복사하고 PyRSSGen2를 설치 한 후 쿠분투 11.10에서 실행하고 문제없이 코드를 생성했습니다. test.xml 파일을 살펴보면 다음과 같습니다.

<?xml version="1.0" encoding="utf-8"?> 
    <rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/"> 
    <channel> 
     <title>Example Title</title> 
     <link>http://example.com</link> 
     <description>Example RSS Output</description> 
     <pubDate>Thu, 27 Oct 2011 05:36:27 GMT</pubDate> 
     <lastBuildDate>Thu, 27 Oct 2011 05:36:27 GMT</lastBuildDate> 
     <generator>PyRSS2Gen-1.0.0</generator> 
     <docs>http://blogs.law.harvard.edu/tech/rss</docs> 

     <item> 
      <title>Item Title</title> 
      <link>http://example.com</link> 
      <media:thumbnail url="http://example.com/image.jpg"></media:thumbnail> 
      <description>< ![CDATA[<p><b>example</b>text<p><br/> 
    <p>Where are you going today?</p> 
    ]]></description> 
      <guid>random_guid_x9129319</guid> 
      <pubDate>Thu, 27 Oct 2011 14:36:27 GMT</pubDate> 
     </item> 
    </channel> 
    </rss> 

나는 그 코드가 어떻게 작동 하는지를 후손을 위해 설명하려고합니다.

위의 ViennaMike와 매우 비슷하게 PyRSS2Gen은 자동으로 HTML을 이스케이프 처리하는 내장 된 SAX 라이브러리를 사용합니다. 그러나이 문제를 해결할 수있는 방법이 있습니다. 언급 한 코드에서 PyRSS2Gen의 "RSSItem"을 오버로드하여 "설명"을 출력 할 때 실제로 아무 것도 출력하지 않도록했습니다. (이것은 "NoOutput"클래스가 포함 된 것입니다.)

설명이 출력되지 않으므로 출력에 직접 첨부하는 방법을 추가해야합니다. 따라서 "publish_extensions"코드 (media_thumbnail 태그와 description 태그를 모두 출력 함).

나는 (미디어 썸네일 클래스가 필요하지 않으므로) 다소 혼란스러워서 수업을 다시 작성하여 "Media Thumbnail"수업이 없으므로 혼란 스러울 수 있습니다. .

# This is insecure, and only here for a proof of concept. Your mileage may vary. Et cetra. 
import PyRSS2Gen 
import datetime 

class NoOutput: 
    def __init__(self): 
     pass 
    def publish(self, handler): 
     pass 

class IPhoneRSS2(PyRSS2Gen.RSSItem): 
    def __init__(self, **kwargs): 
     PyRSS2Gen.RSSItem.__init__(self, **kwargs) 

    def publish(self, handler): 
     self.do_not_autooutput_description = self.description 
     self.description = NoOutput() # This disables the Py2GenRSS "Automatic" output of the description, which would be escaped. 
     PyRSS2Gen.RSSItem.publish(self, handler) 

    def publish_extensions(self, handler): 
     handler._out.write('<%s>< ![CDATA[%s]]></%s>' % ("description", self.do_not_autooutput_description, "description")) 

# How to use: 

rss = PyRSS2Gen.RSS2(
    title = "Example Title", 
    link="http://example.com", 
    description="Example RSS Output", 
    lastBuildDate=datetime.datetime.utcnow(), 
    pubDate=datetime.datetime.utcnow(), 
    items=[ 
     IPhoneRSS2(
     title="Item Title", 
     description="""<p><b>example</b>text<p><br/> 
<p>Where are you going today?</p> 

""", 
     link="http://example.com", 
     guid="random_guid_x9129319", 
     pubDate=datetime.datetime.now()), 
    ] 
) 
rss.rss_attrs["xmlns:media"] = "http://search.yahoo.com/mrss/" 
rss.write_xml(open("test.xml", "w"), "utf-8") 

피드에 이미지를 포함시키고 싶습니다. description 태그에 이미지 용 HTML을 포함 시키시겠습니까? 아니면 다른 곳에 있습니까? 그것이 다른 곳에 있다면, 상황에 맞는 적절한 수정을 할 수 있도록 샘플 RSS 피드를 제공 할 수 있습니까?

0

jbm 님의 답변이 좋다. 그냥 추가 업 : Python2.7.5는 색소폰 라이브러리를 변경, 그래서 우리는 JBM의 코드를 수정해야합니다 (

def publish_extensions(self, handler): 
    handler._write('<%s><![CDATA[%s]]></%s>' % ("description", self.do_not_autooutput_description, "description"))