I am doing a scraping project with BeautifulSoup, for which I have created a dictionary within a for loop so that this cycle is repeated for all the containers of the website from which I am scraping them, it prints everything correct in the terminal.
The problem is when I want to display the data from this dictionary in an HTML template, if I use:
{% for b in buscar %}
And I start calling each of the dictionary values to sort them into a container with
{{ b.nombre }}
When executing it, it shows me the empty container repeating the number of times as values the dictionary has.
I understand that it is an error in the HTML loop because in the views everything works fine for me. And if I don't put the for loop in HTML it just shows me the last scraped element.
Here I leave the code of views.py
busqueda = dict()
product_list = soup.find_all('div', attrs= {'class':'grid-item'})
for product in product_list:
busqueda['imagen'] = product.find('img', attrs= {'class':'no-js','srcset':True})
busqueda['nombre'] = product.find('p').text
busqueda['precio'] = product.find('small', attrs= {'aria-hidden':'true'}).text
sleep(randint(3, 5))
print(busqueda)
context = {"buscar": busqueda}
return render(request, "index.html", context)
code in html
{% for b in buscar %}
<div class="card" style="width: 18rem; margin-left: 5px; margin-right: 5px;">
<img src="{{ b.imagen }}" class="card-img-top">
<div class="card-body">
<h5 class="card-title">{{ b.nombre }}</h5>
<p class="card-text">{{ b.precio }}</p>
</div>
</div>
{% endfor %}
In this case, the .card container would be displayed 3 times for the 3 values that
tiene el diccionario (imagen, nombre, precio).
I would really appreciate it if you could help me, I've been at this for days.
Dear Milo.7725
I identify 2 problems in your code:
product_list
contains multiple products what you want to show is the information of those productsIf the problem is that we can correct it in the following way:
If the above is not the approach that your application has, we proceed to the next point
Example:
The result you get is:
In any case, if what you want is to obtain its value, you have to do the following:
As you can see, the code above only operates on the elements of a dictionary, that is, for each key, value you would have a card and I don't think that is your approach
I'm waiting for your comments
Cheers!