Python FeedParser很好地格式化了Reddit

2024-05-19 07:05:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个程序,打印出前5个笑话从/r/笑话,但我有一些问题格式化它看起来很好。我想这样安排。在

Post Title: Post Content

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

^{pr2}$

我正在打印标题,后面跟着一个冒号和一个空格,然后是描述。但是它打印所有文本,包括链接、作者和所有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个条目。我需要做的是格式化冒号后面的描述字符串,以便只包括段落标记中的文本。在


Tags: https文本程序comtitlewwwdescriptionpost
2条回答

你可以用漂亮的肥皂包来做这件事

Link to documention

from bs4 import BeautifulSoup 
soup = BeautifulSoup(html_doc, 'html.parser') 
print(soup.get_text())

Oren使用beauthoulsoup是正确的,但我将尝试提供更完整的答案。在

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部分获取文本。在

相关问题 更多 >

    热门问题