【发布时间】:2011-02-27 15:15:57
【问题描述】:
我正在测试用 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))
【问题讨论】:
标签: python django django-templates screen-scraping django-views