Skip to main content
 首页 » 编程设计

Python FeedParser 格式 Reddit Nicely

2024年10月24日14cyq1162

我正在尝试创建一个程序来打印出/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 部分获取文本。