2012-08-28 30 views
1

我目前正在嘗試使用Scrapey在python中創建一個簡單的爬蟲程序。我想要它做的是讀取鏈接列表並保存它們鏈接到的網站的html。現在,我可以獲取所有網址,但我無法弄清楚如何下載網頁。這裏是我的蜘蛛到目前爲止的代碼:用scrapy創建一個簡單的python爬蟲程序

from scrapy.spider import BaseSpider 
from scrapy.selector import HtmlXPathSelector 
from tutorial.items import BookItem 

# Book scrappy spider 

class DmozSpider(BaseSpider): 
    name = "book" 
    allowed_domains = ["learnpythonthehardway.org"] 
    start_urls = [ 
     "http://www.learnpythonthehardway.org/book/", 
    ] 

    def parse(self, response): 
     filename = response.url.split("/")[-2] 
     file = open(filename,'wb') 
     file.write(response.body) 
     file.close() 

     hxs = HtmlXPathSelector(response) 
     sites = hxs.select('//ul/li') 
     items = [] 
     for site in sites: 
      item = BookItem() 
      item['title'] = site.select('a/text()').extract() 
      item['link'] = site.select('a/@href').extract() 
      items.append(item) 
     return items 

回答

1

在你parse方法,在返回的項目列表中返回Request對象觸發下載:

for site in sites: 
    ... 
    items.append(item) 
    items.append(Request(item['link']), callback=self.parse) 

這將導致該履帶產生BookItem爲每個鏈接,但也遞歸併下載每本書的頁面。當然,如果您想分解不同的子頁面,可以指定不同的回調(例如self.parsebook)。