使用Python中的Feedparser解析相同名称元素的Stackoverflow RSS作业源

时间:2017-10-28 14:13:47

标签: python rss feedparser

Stackoverflow RSS源上的每个作业项都有某些标签,键和#34;类别"。

基本上看起来像这样:

<category>scala</category>
<category>hadoop</category>
<category>apache-spark</category>
<category>hive</category>
<category>json</category>

我想使用Feedparser将所有标签放入列表中。相反,我总是得到第一个元素。 Feedparser文档提到entries[i].content,但我不确定这是正确的方法,还是在这种情况下如何使用它。

这是我的代码:

import feedparser

rss_url = "https://stackoverflow.com/jobs/feed"
feed = feedparser.parse(rss_url)
items = feed["items"]

for item in items:
    title = item["title"]
    try:
        tags = []
        tags.append(item["category"])
        print(title + " " + str(tags))
    except:
        print("Failed")

1 个答案:

答案 0 :(得分:2)

feedparser项目的

category基本上是tags列表中第一个元素的别名,它基本上是一个包含更多feedparser项目的列表,每个项目都包含term属性,其中包含标签名称。

您可以直接访问这些条款:

categories = [t.term for t in item.get('tags', [])]

对于您的代码:

for item in items:
    title = item["title"]
    categories = [t.term for t in item.get('tags', [])]
    print(title, ', '.join(categories))

请参阅entries[i].tags documentation