我是撰写您列出的博客文章的人。在安装 PyRSSGen2 之后,我从 gist 中复制了代码并在 Kubuntu 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 使用内置的 SAX 库,它会自动转义 HTML。但是,有一些方法可以解决这个问题。在您提到的代码片段中,我覆盖了 PyRSS2Gen 的“RSSItem”,因此当它输出“描述”时,它实际上不会输出任何内容。 (这就是包含“NoOutput”类的原因)。
由于没有输出描述,我们必须自己添加一个方法将其附加到输出。因此,“publish_extensions”代码(输出 media_thumbnail 和描述标签)。
我可以看到它有些令人困惑(因为您不需要 media_thumbnail 类)所以我继续并重新编写了该类,因此没有“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")
您提到要在 Feed 中添加图片;您是在描述标签中包含图像的 HTML,还是在其他地方?如果它在其他地方,您能否提供一个示例 RSS 提要,以便我可以根据您的情况进行适当的更改?