问题
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