为什么Scrapy只爬一页?

时间:2012-03-21 04:42:59

标签: scrapy

我正在尝试针对抓取网页测试Scrapy,我不明白为什么我的抓取工具只抓取一个页面,我试图评论规则和allowed_domains但没有成功。我想有一些愚蠢的东西,我错过任何帮助都会被欣赏。

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

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

1 个答案:

答案 0 :(得分:6)

您使用规则的回调。来自docs

  

follow是一个布尔值,指定是否应该遵循链接   使用此规则提取的每个响应。如果回调为无,请关注   默认为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

  

必须返回包含Item和/或Request对象(或其中任何子类)的列表

你的方法都没有这样做。 example很好地证明了这一点。如果您覆盖parse,则仍需要返回正确的项目/请求。