我应该如何在 Django 中显示 BeautifulSoup 解析的结果? [英] How should I show results of BeautifulSoup parsing in Django?
问题描述
我正在尝试使用 BeautifulSoup 和 Django 抓取网页.这是我执行此任务的 views.py:
I'm trying to scrape a web page using BeautifulSoup and Django. Here's my views.py which do this task:
def detail(request, article_id):
article = get_object_or_404(Article, pk=article_id)
html = urllib2.urlopen("...url...")
soup = BeautifulSoup(html)
title = soup.title
return render(request, 'detail.html', {'article': article, 'title':title})
但是当我在 Django 模板文件中使用 {{ title }} 时,它没有显示任何内容.我已经测试过了,它在 shell 中工作.我在这个函数中添加了一行:
But when I use {{ title }} in django template files, it doesn't show anything. I've test it and it works in shell. I've added a line to this function:
print soup.title
每次我重新加载页面时它都会打印它,但它没有显示在模板中.
and it prints it every time I reload the page, but it doesn't show up in templates.
对于其他一些命令,例如 find_all("a") 或 prettify 方法,内容也显示得很奇怪.谁能告诉我如何在django模板中正确打印beautifulsoup的结果?
The content also displayed very strange for some other commands like: find_all("a") or prettify method. Could anyone tell me how can I print the result of beautifulsoup correctly in django templates?
推荐答案
你打印出来的结果是什么?
what's the result that you print out?
你试过用这个吗?
soup.title.string
如果您必须将 html 发送到模板,请尝试:
if you have to send html in to templates try:
{% autoescape off %}{{ title }}{% endautoescape %}
这篇关于我应该如何在 Django 中显示 BeautifulSoup 解析的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!