显示网页中的所有链接

2024-09-29 11:21:00 发布

您现在位置:Python中文网/ 问答频道 /正文

这里是视图.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})

这里是主页.html你知道吗

{{ result }}

And output I got:


Tags: fromimportcomurl链接requestwwwlinks
2条回答

您的结果只包含最后一个链接.附加将其发送到循环中的列表,然后将列表发送到模板。你知道吗

现在你的结果只有最后一个链接。你知道吗

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

这会有用的。。 您的列表(list1)将如下所示。 ['www.google.com','www.new.com','…..','…..']

在模板中,可以循环使用结果变量来打印每个链接。(.html文件)

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

试试这个。你知道吗

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

使用正确的变量名。。。:)

相关问题 更多 >