oce*_*800 4 python web-crawler scrapy scrapy-spider
所以我正在尝试使用CrawlSpider并理解Scrapy Docs中的以下示例:
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class MySpider(CrawlSpider):
name = 'example.com'
allowed_domains = ['example.com']
start_urls = ['http://www.example.com']
rules = (
# Extract links matching 'category.php' (but not matching 'subsection.php')
# and follow links from them (since no callback means follow=True by default).
Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),
# Extract links matching 'item.php' and parse them with the spider's method parse_item
Rule(LinkExtractor(allow=('item\.php', )), callback='parse_item'),
)
def parse_item(self, response):
self.logger.info('Hi, this is an item page! %s', response.url)
item = scrapy.Item()
item['id'] = response.xpath('//td[@id="item_id"]/text()').re(r'ID: (\d+)')
item['name'] = response.xpath('//td[@id="item_name"]/text()').extract()
item['description'] = response.xpath('//td[@id="item_description"]/text()').extract()
return item
Run Code Online (Sandbox Code Playgroud)
然后给出的描述是:
这个蜘蛛会开始抓取example.com的主页,收集类别链接和项链接,使用parse_item方法解析后者.对于每个项目响应,将使用XPath从HTML中提取一些数据,并且将使用它填充项目.
我理解,对于第二条规则,它从中提取链接item.php,然后使用该parse_item方法提取信息.但是,第一条规则的目的究竟是什么?它只是说它"收集"链接.这意味着什么,如果他们没有从中提取任何数据,为什么有用呢?
例如,在搜索帖子的论坛或搜索产品页面时对在线商店进行分类时,CrawlSpider非常有用.
这个想法是"不知何故"你必须进入每个类别,搜索与你想要提取的产品/项目信息相对应的链接.这些产品链接是在该示例的第二个规则中指定的链接(它表示item.php在URL 中具有的链接).
现在蜘蛛应该如何继续访问链接,直到找到包含链接item.php?这是第一个规则.它说要访问包含category.php但不包含的每个链接subsection.php,这意味着它不会从这些链接中精确提取任何"项目",但它定义了蜘蛛的路径以查找真实项目.
这就是为什么你看到它不包含callback规则内部的方法,因为它不会返回你要处理的链接响应,因为它将被直接遵循.