我正在测试用 django 构建一个抓取网站。由于某种原因,以下代码仅提供一张图片图像,我希望它打印每个图像、每个链接和每个价格,有帮助吗? (另外,如果你们知道如何将这些数据放入数据库模型中,这样我就不必总是抓取网站,我洗耳恭听,但这可能是另一个问题)干杯!
这是模板文件:
{% extends "base.html" %}
{% block title %}Boats{% endblock %}
{% block content %}
<img src="{{ fetch_boats }}"/>
{% endblock %}
这是views.py 文件:
#views.py
from django.shortcuts import render_to_response
from django.template.loader import get_template
from django.template import Context
from django.http import Http404, HttpResponse
from fetch_images import fetch_imagery
def fetch_it(request):
fi = fetch_imagery()
return render_to_response('fetch_image.html', {'fetch_boats' : fi})
这是 fetch_images 模块:
#fetch_images.py
from BeautifulSoup import BeautifulSoup
import re
import urllib2
def fetch_imagery():
response = urllib2.urlopen("http://www.boattrader.com/search-results/Type")
html = response.read()
#create a beautiful soup object
soup = BeautifulSoup(html)
#all boat images have attribute height=165
images = soup.findAll("img",height="165")
for image in images:
return image['src'] #print th url of the image only
# all links to detailed boat information have class lfloat
links = soup.findAll("a", {"class" : "lfloat"})
for link in links:
return link['href']
#print link.string
# all prices are spans and have the class rfloat
prices = soup.findAll("span", { "class" : "rfloat" })
for price in prices:
return price
#print price.string
最后,如果需要,urlconf 中的映射 URL 如下:
from django.conf.urls.defaults import *
from mysite.views import fetch_it
urlpatterns = patterns('', ('^fetch_image/$', fetch_it))
最佳答案
您的 fetch_imagery
函数需要一些工作 - 因为您要返回(而不是使用 yield
),所以第一个 返回 image['src']
将终止函数调用(我假设所有这些返回都是代码所示的同一函数定义的一部分)。
此外,我的假设是您将从 fetch_imagery
返回一个列表/元组(或定义生成器方法),在这种情况下您的模板需要如下所示:
{% block content %}
{% for image in fetch_boats %}
<img src="{{ image }}" />
{% endfor %}
{% endblock %}
这基本上会循环列表中的所有项目(在您的情况下为图像网址),并为每个项目创建 img
标签。
关于python - 在 Django 模板中显示抓取的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2971637/