2012-08-28 31 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)。