2012-03-21 136 views
1

我试图测试Scrapy爬行网页,我不明白为什么我的爬虫只爬行一页,我试图评论规则和allowed_domains都没有成功。我想有一些愚蠢的我失去了任何帮助,将不胜感激。为什么Scrapy只抓取一个页面?

from scrapy.contrib.spiders import CrawlSpider, Rule 
from scrapy.spider import BaseSpider 
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor 

class NYSpider(CrawlSpider): 
    name = "ny" 
    allowed_domains = ["nytimes.com"] 
    start_urls = ["http://www.nytimes.com/"] 

    rules = (
     Rule(SgmlLinkExtractor(allow=('/2012',)), callback='parse_article'), 
     Rule(SgmlLinkExtractor(allow=('/page',))), 
    ) 

    def parse(self, response): 
     print 'page '+response.url 

    def parse_article(self, response): 
     print 'article '+response.url 

任何抓取整个网站的程序样本都会受到欢迎。

回答

6

对规则使用回调。从docs

遵循的是一个布尔值,指定如果链接应该从 这一规则提取每个响应之后。如果回调为无,请按照 默认为True,否则默认为False。

所以,你应该做的

Rule(SgmlLinkExtractor(allow=('/2012',)), callback='parse_article', follow=True) 

此外这个问题,另一个IMO可能是你的parse method

Warning 
When writing crawl spider rules, avoid using parse as callback, since the CrawlSpider uses the parse method itself to implement its logic. So if you override the parse method, the crawl spider will no longer work. 

虽然你不使用回调中这种方法,你可能重写超类(CrawlSpider)中的方法。因此重新分析你的分析方法可能会奏效。

的另一个问题是,你没有返回在你的方法

ItemRequest必须返回一个包含项目和/或请求的对象列表(或他们的任何子类)

你的方法都没有做到这一点。 example表明这非常好。如果您覆盖parse,则仍需要返回适当的项目/请求。

+0

谢谢,但这并没有改变任何东西 – AsTeR 2012-03-21 11:08:37

+0

@AsTeR做了另一个猜测;)看看我的编辑,如果这对你有用。 – DrColossos 2012-03-21 11:13:48

+0

谢谢。不,它不会,调用父级引发异常:exceptions.NotImplementedError。我认为解析方法的实现是让子类的。 – AsTeR 2012-03-21 12:55:59