2016-11-25 297 views
1

這裏是views.py。我想顯示'www.pythonforbeginners.com'中包含的所有鏈接,但問題是它只顯示頁面的最後一個鏈接。我該如何解決它?顯示網頁上的所有鏈接

from django.shortcuts import render 
from bs4 import BeautifulSoup 
import urllib2 

def home(request): 
    url = urllib2.urlopen("http://www.pythonforbeginners.com") 
    readurl = url.read() 
    soup = BeautifulSoup(readurl) 
    links = soup.find_all('a') 
    for lin in links: 
     result = lin.get('href') 

    return render(request, 'search/homepage.html', {'result': result, 'url':url}) 

這裏是homepage.html

{{ result }} 

And output I got:

+0

你正在做一個迭代,所以'links'集合的最後一個元素(隱私策略)被分配給'result'變量。最好將該集合或其清理過的表單傳遞給您的模板文件。 – marmeladze

回答

4

試試這個。

def test(request): 
    url = urllib2.urlopen("http://www.pythonforbeginners.com") 
    readurl = url.read() 
    soup = BeautifulSoup(readurl) 
    links = soup.find_all('a') 
    result = [] 
    for lin in links: 
     result.append(lin.get('href')) 

    return render(request, 'portal_test.html', {'result': result, 'url': url}) 

你正在做的是重寫結果數據。您必須使用列表並獲取其中的所有數據。然後在模板中使用,

{% for x in result %} 
{{ x }} 
{% endfor %} 

使用正確的變量名... :)

1

你的結果只包含最後link.Append它在循環列表,然後發送列表中的模板。

現在你的結果只有最後一個鏈接。

from django.shortcuts import render 
from bs4 import BeautifulSoup 
import urllib2 

def home(request): 
    url = urllib2.urlopen("http://www.pythonforbeginners.com") 
    readurl = url.read() 
    soup = BeautifulSoup(readurl) 
    links = soup.find_all('a') 
    list1 = [] 
    for lin in links: 
     result = lin.get('href') 
     list1.append(result) 

    return render(request, 'search/homepage.html', {'result': list1,'url':url}) 

這將工作.. 你的列表(列表1)將是這個樣子。 ['www.google.com','www.new.com','....','....']

在模板中,您可以遍歷結果變量來打印每個鏈接。 (.html文件)

{% for x in result %} 
{{ x }} 
{% endfor %} 
相關問題