我得到了头衔和网址。如何建立链接?

时间:2014-05-18 17:47:59

标签: python django python-2.7

我有新闻标题和网址。如何进入链接?

这就是我提取标题和网址的方法:

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})

这是我的HTML:

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

我想你已经知道这种制作链接了。那么,做到这一点的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

尝试这样的事情怎么样?

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
        ...

然后模板将是:

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

如果你想坚持使用两个列表,那么你应该只看一眼this question