我正在尝试创建一个程序,打印出/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/