How should I show results of BeautifulSoup parsing in Django?

1.7k views Asked by At

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?

2

There are 2 answers

0
Ben Hsieh On BEST ANSWER

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 %}
0
Vikas Ojha On

Change the following -

title = soup.title

to -

title = soup.title.text