我正在尝试测试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
Run Code Online (Sandbox Code Playgroud)
任何对整个站点进行爬行的程序样本也会受到欢迎.
您使用规则的回调.来自文档:
follow是一个布尔值,指定是否应该从使用此规则提取的每个响应中跟踪链接.如果回调为None,则默认为True,否则默认为False.
所以你应该这样做
Rule(SgmlLinkExtractor(allow=('/2012', )), callback='parse_article', follow=True)
Run Code Online (Sandbox Code Playgroud)
除此问题外,另一个IMO可能是您的解析方法:
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.
Run Code Online (Sandbox Code Playgroud)
虽然您不在回调中使用此方法,但您可以从超类(CrawlSpider)覆盖该方法.所以重命名你的解析方法可能会有效.
另一个问题是您没有返回Item或Request在您的方法中
必须返回包含Item和/或Request对象(或它们的任何子类)的列表
你的方法都没有这样做.这个例子很好地证明了这一点.如果覆盖parse,仍然需要返回正确的项目/请求.