Home > Net >  Python Variables in HTML
Python Variables in HTML

Time:04-14

I recently coded a script that scrapes headlines and images off of enter image description here

As you can see, instead of displaying the images in order by its corresponding headline, its just displaying ALL of the images in every single headline.

All i need is for each image from the 10 images seen in the screenshot i put up above to show one by one in order next to each headline.

Here's the code for the container element that is displaying the headlines and images in my html file :

<div >
        <center><i><u><h3 >Live News from The Toronto Star</h3></u></i></center>
        {% for n in toi_news %}
        <strong><h5>{{n}}</h5></strong>
        {% for i in images %}
        <img src="{{i}}">
        {% endfor %}
        <hr>
        {% endfor %}
        <br>
    </div>

Can anyone help me? Any help would be greatly appreciated.

CodePudding user response:

You need to loop through the images and the headlines concurrently not nesting the image loop in the headline loop.

<div >
    <center><i><u><h3 >Live News from The Toronto Star</h3></u></i></center>
    {% for i, n in zip(images, toi_news) %}
    <strong><h5>{{n}}</h5></strong>
    <img src="{{i}}">
    <hr>
    {% endfor %}
    <br>
</div>

If you cant you the above syntax you can loop over an index for both lists

<div >
    <center><i><u><h3 >Live News from The Toronto Star</h3></u></i></center>
    {% for x in range(len(toi_news)) %}
    <strong><h5>{{toi_news[x]}}</h5></strong>
    <img src="{{images[x]}}">
    <hr>
    {% endfor %}
    <br>
</div>
  • Related