-2

I have news titles and urls. How to make it to the link?

This is how I extract titles and urls:

def Save(request):
    news = []
    links = []
    url ="http://www.basketnews.lt/lygos/59-nacionaline-krepsinio-asociacija/2013/naujienos.html"
    r = requests.get(url)
    soup = BeautifulSoup(r.content)
    nba = soup.select('div.title > a')
    for i in reversed(nba):
        news.append(i.text) # Here I have list of titles
        links.append(i["href"]) # list of urls
            # Here I'm saving that info to my model. Ignore it
            save_it = Naujienos(title = i.text, url = "Basketnews.lt" + i['href']) # 
            save_it.save()

        return render(request, 'Titles.html', {'news': news, "links": links})

Here is my HTML:

{% for i in news%}
    {% for o in links%}
        <a href={{o}}>{{i}}</a> 
    {% endfor %} 
{% endfor %} 

As I suppose you already know that this kind of making links is worng. So, what is the right way to do it?

Irmantas Želionis
  • 2,194
  • 3
  • 17
  • 30

1 Answers1

1

How about trying something like that?

from collections import namedtuple

Link = namedtuple('Link', ['title', 'url'], verbose=True)


def Save(request):
    ...
    for i in reversed(nba):
        links.append(Link(title=i.text, url=i["href"])) # list of urls
        ...

Then template would be:

{% for link in links %}
    <a href="{{link.url}}">{{link.title}}</a> 
{% endfor %}

And if you want to stick with two lists, then you should have a glance at this question.

Community
  • 1
  • 1
Allactaga
  • 193
  • 1
  • 7