python - 使用 feedparser/RSS,如何在 django 中将 feed 对象从 views.py 传递到 .html?
问题描述
我正在尝试向我的 Web 应用程序添加一个简单的 RSS 解析器。目标是获取一个 RSS 频道并在单个页面上显示来自该频道的新闻。我设法为单个对象执行此操作,但不能为许多对象(例如 10 个)执行此操作。
该项目假设我有文件views.py
和RSS.html
.
以下 IS 代码适用于单个解析对象。
views.py
:
import feedparser
def rss(request):
feeds = feedparser.parse("https://www.informationweek.com/rss_simple.asp")
entry = feeds.entries[0]
return render(
request,
'posts/rss.html',
feeds={
'title': entry.title,
'published': entry.published,
'summary': entry.summary,
'link': entry.link,
'image':entry.media_content[0]['url']
}
)
RSS.html
:
<h3>{{ title }}</h3>
<i>Date: {{ published }}<p></i>
<b>Summary:</b><p> {{ summary }}<p>
<b>Link:</b><a href="{{ link }}"> {{ link }}</a><p>
<b>Image:</b><p><img src="{{ image }}"></img><p>
我不明白如何将所有提要传递到 RSS.html。
我尝试通过视图传递它,但它不起作用。
以下是不起作用的代码:
views.py
:
return render(request, 'posts/rss.html', feeds)
RSS.html
{% for entry in feeds %}
<li><a href="{{entry.link}}">{{entry.title}}</a></li>
{% endfor %}
解决方案
将提要对象传递给模板时,您必须遍历entries
提要对象的字段:
Python:
import feedparser
def rss(request):
feed = feedparser.parse("https://www.informationweek.com/rss_simple.asp")
return render(request, 'posts/rss.html', {'feed': feed})
HTML:
{% for entry in feed.entries %}
<li><a href="{{entry.link}}">{{entry.title}}</a></li>
{% endfor %}
一般文件:
条目文档:
字典列表。每个字典都包含来自不同条目的数据。条目按照它们在原始提要中出现的顺序列出。
推荐阅读
- svelte - Culori js 适用于 Svelte REPL 但不适用于本地项目
- javascript - React JS 路由:从一页中省略一些组件
- r - 在 R 中将 JSON 文件转换为可用的数据框
- python - 如何在 Mac 上从 python 解决 ssl.SSLCertVerificationError
- c++ - Qt 中是否有任何功能可以编辑 JSON 文件?
- javascript - 如何在密码保护页面上根据 PHP 服务器响应运行 JavaScript?
- php - 删除 php url 无法在我的 XAMPP localhost 上运行,但可以在服务器上运行
- excel-formula - 收到索引匹配的参考错误,我做错了什么?
- python - 使用转义 t "\t" 格式化时未对齐
- algorithm - 查询子字符串的数据结构,包含字符串集合中的子字符串