django로 스크래핑 사이트를 구축하는 테스트입니다. 몇 가지 이유로 다음 코드는 모든 이미지, 모든 링크 및 모든 가격, 모든 도움말을 인쇄하고 싶습니다. (또한 사람들이이 데이터를 데이터베이스 모델에 저장하는 방법을 알고 있으므로 항상 사이트를 다 쓸 필요는 없습니다. 나는 모든 귀이지만 다른 질문 일 수 있습니다) 건배!Django 템플릿에서 스크랩 된 결과 표시
다음#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 모듈입니다 : 여기
{% extends "base.html" %}
{% block title %}Boats{% endblock %}
{% block content %}
<img src="{{ fetch_boats }}"/>
{% endblock %}
는 views.py 파일입니다 : 여기
템플릿 파일입니다
#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))
감사 Rishabh 인스, 나는 다른 사람에 대한 (여전히 오히려 초보자) ... 전에 yield 문을 보지 않았다면 그건
가 여기에 yield 문에 대한 좋은 대답 : HTTP ://stackoverflow.com/questions/231767/can-somebody-explain-me-the-python-yield-statement – Diego