我有新闻标题和网址。如何进入链接?
这就是我提取标题和网址的方法:
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 %}
我想你已经知道这种制作链接了。那么,做到这一点的正确方法是什么?
答案 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。