Python FeedParser 很好地格式化 Reddit

标签 python xml rss reddit feedparser

我正在尝试创建一个程序,打印出/r/Jokes 中的前 5 个笑话,但在将其格式化为好看的格式时遇到了一些问题。我想把它设置成这样。

Post Title: Post Content

例如,以下是直接来自 RSS 提要的笑话之一:

<item>

    <title>What do you call a stack of pancakes?</title>

    <link>https://www.reddit.com/r/Jokes/comments/3ix348/what_do_you_call_a_stack_of_pancakes/</link>

    <guid isPermaLink="true">https://www.reddit.com/r/Jokes/comments/3ix348/what_do_you_call_a_stack_of_pancakes/</guid>

    <pubDate>Sun, 30 Aug 2015 03:18:00 +0000</pubDate>

    <description><!-- SC_OFF --><div class="md"><p>A balanced breakfast</p> </div><!-- SC_ON --> submitted by <a href="http://www.reddit.com/user/TheRealCreamytoast"> TheRealCreamytoast </a> <br/> <a href="http://www.reddit.com/r/Jokes/comments/3ix348/what_do_you_call_a_stack_of_pancakes/">[link]</a> <a href="https://www.reddit.com/r/Jokes/comments/3ix348/what_do_you_call_a_stack_of_pancakes/">[2 comments]</a></description>

</item>

我当前正在打印标题,后跟冒号和空格,然后是描述。但是它会打印所有文本,包括链接、作者和所有 HTML 标签。我如何获取段落标签内的文本。

谢谢

编辑:这是我的代码:

d = feedparser.parse('https://www.reddit.com/r/cleanjokes/.rss')
print("")
print("Pulling latest jokes from Reddit. https://www.reddit.com/r/cleanjokes")
print("")
time.sleep(0.8)
print("Displaying First 5 Jokes:")
print("")
print(d['entries'][0]['title'] + ": " + d['entries'][0]['description'])
print(d['entries'][1]['title'] + ": " + d['entries'][1]['description'])
print(d['entries'][2]['title'] + ": " + d['entries'][2]['description'])
print(d['entries'][3]['title'] + ": " + d['entries'][3]['description'])
print(d['entries'][4]['title'] + ": " + d['entries'][4]['description'])

这仅获取前 5 个条目。我需要做的是将冒号后的描述字符串格式化为仅包含段落标记内的文本。

最佳答案

Oren关于使用 BeautifulSoup 是正确的,但我会尝试提供更完整的答案。

d['entries'][0]['description'] 返回 html,您需要对其进行解析。 bs是一个很棒的图书馆。

您可以使用以下方式安装它:

pip install beautifulsoup4

from bs4 import BeautifulSoup 
soup = BeautifulSoup(d['entries'][0]['description'], 'html.parser') 
print(soup.div.get_text())

从条目的 div 部分获取文本。

关于Python FeedParser 很好地格式化 Reddit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32298542/

相关文章:

python - 循环python的迭代

python - cURL (pycurl) 通过 HTTP 代理的 FTP

对变量中可能存在 None 的类进行排序的 Pythonic 方式

javascript - 使用 javascript 更改现有的 xml prolog

python - Django 模型和遗留类集成

xml - xpath where 子句

java - OpenClover 解析 XML 输出。 java

c# - 使用 c# mvc4 阅读 rss 提要

java - 我的应用程序运行良好,除了 android 9 版本。我不明白是什么问题

css - 如何将 CSS 引用添加到 .NET SyndicationFeed?