How should I show results of BeautifulSoup parsing in Django?

一曲冷凌霜 提交于 2021-02-07 10:16:33

问题


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})

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.

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?


回答1:


what's the result that you print out?

have you try to use this?

soup.title.string

if you have to send html in to templates try:

{% autoescape off %}{{ title }}{% endautoescape %}



回答2:


Change the following -

title = soup.title

to -

title = soup.title.text


来源:https://stackoverflow.com/questions/30788850/how-should-i-show-results-of-beautifulsoup-parsing-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!