如何显示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屋!