feedparser 属性错误

-2 投票
1 回答
2680 浏览
提问于 2025-04-18 12:18

我正在尝试从BBC的RSS源获取一些新闻,并把某些部分保存在本地的XML文件中(虽然现在这段代码只是打印出来)。我似乎能获取到我想要的所有内容,除了pubDate。我遇到了这个错误:

"File "/Library/Python/2.7/site-packages/feedparser.py", line 416, in __getattr__
raise AttributeError, "object has no attribute '%s'" % key
AttributeError: object has no attribute 'pubDate'"

我不太明白为什么,其他我想获取的内容都没有问题。以下是我的代码:

import feedparser
import xml.etree.cElementTree as ET
from xml.dom import minidom

BBCHome = feedparser.parse ('http://feeds.bbci.co.uk/news/rss.xml')


def prettify(elem):

    rough_string = ET.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="  ")

root = ET.Element('root')

for story in BBCHome.entries:
    item = ET.SubElement(root,'item')
    title = ET.SubElement(item,'title')
    title.text = story.title
    # why doesn't pubDate work?
    pubDate = ET.SubElement (item,'pubDate')
    pubDate.text = story.pubDate
    description = ET.SubElement(item,'description')
    description.text = story.description
    link = ET.SubElement(item,'link')
    link.text = story.link
    print prettify(root)

我在阅读这个页面:https://pythonhosted.org/feedparser/namespace-handling.html,我觉得这可能和命名空间有关,但说实话我并不太理解。

我查看了原始的RSS源,发现pubDate似乎只是item的另一个子元素,和description或title类似。

如果我能找到解决这个问题的方法,以及为什么它不工作的原因,我会非常感激。谢谢。

1 个回答

4

我打印了 story.keys(),结果只得到了。

['summary_detail', 'published_parsed', 'links', 'title', 'media_thumbnail',
 'summary', 'guidislink', 'title_detail', 'href', 'link', 'published', 'id']

也许 story.published 是你需要的内容。

撰写回答