python - 如何从 feedparser 解析的 feed 文章中渲染 django 模板中的 html 内容

标签 python django

我正在解析提要网址并获取文章内容。但是,当我尝试将内容呈现到 HttpResponse 中的 html 页面时,内容中的 html 元素或标签将按原样呈现,就像其余内容一样。在将其渲染到 django 模板之前,我是否必须处理内容以显示其中的 html 内容?

此外,如何获取给定提要的图标并在 django 模板中呈现。

我是 django 和 python 的新手。我不知道该怎么做。

我正在使用 feedparser 来解析 feed url。

我正在使用以下代码从文章内容中获取网址列表。 现在,我应该如何获取 favicon url,因为某些内容中的 favicon 呈现为 .png 格式,并且有几个 .png 链接。如何区分哪个是favicon?

import feedparser
import lxml.html as lh
import urllib2

#Import Feed for Parsing
d = feedparser.parse("http://www.popgadget.net/atom.xml")

# Print feed name
print d['feed']['title']

# Determine number of posts and set range maximum
posts = len(d['entries'])

# Collect Post URLs
for post in d['entries']:
   link=post['link']
   print('Parsing {0}'.format(link))
   doc=lh.parse(urllib2.urlopen(link))
   imgs=doc.xpath('//img[@class="bpImage"]')
   for img in imgs:
       print(img.attrib['src'])

最佳答案

I am parsing a feed url and getting the article content. But, when i try to render the content to html page in HttpResponse, the html elements or tags in the content are rendered as it is, like rest of the content. Do I have to process the content to display the html stuff in it before rendering it to django template?

我认为 Django 正在转义 feedparser 获取的 HTML。原因是 HTML 可能包含恶意 HTML 并最终包含恶意标签。

如果您确实想显示 feedparser 获取的 HTML 而不进行 Django 转义,请使用 |safe filter .

Also, how to get the favicon for a given feed and render in django template

  1. 下载提要,使用 httplib

  2. 查找图标或 Logo 标签,favicon url 应为标签内容,使用 lxml

  3. 在模板中使用 img 标签显示它

关于python - 如何从 feedparser 解析的 feed 文章中渲染 django 模板中的 html 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9837082/

相关文章:

python - 如何从包含字母数字字符的单个列表创建元组?

python - 使用返回函数中的变量作为另一个函数的参数

python - 这个 `if` 条件是否曾经运行过?

python - django-simple-history,在管理中显示更改的字段

python - 如何防止 Django 覆盖 sessionid cookie?

Python/django继承自2个类

python - 运行 py.test 时出现错误 ImportMismatchError

python - 用 Pandas DataFrame 中月份 (AND - 1) 的值替换月份 IN 的 NaN

python - Django错误: Not environment configured

python - Django 部署。加载 MySQLdb 模块时出错。从/tmp 目录读取/写入时出现问题