首页 文章

Scrapy - 了解CrawlSpider和LinkExtractor

提问于
浏览
1

所以我正在尝试使用CrawlSpider并理解_1410722中的以下示例:

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

然后给出的描述是:

这个蜘蛛会开始抓取example.com的主页,收集类别链接和项链接,使用parse_item方法解析后者 . 对于每个项目响应,将使用XPath从HTML中提取一些数据,并且将使用它填充项目 .

据我所知,对于第二条规则,它从 item.php 中提取链接,然后使用 parse_item 方法提取信息 . 但是,第一条规则的目的究竟是什么?它只是说它是"collects"的链接 . 这意味着什么,如果他们没有从中提取任何数据,为什么有用呢?

1 回答

  • 7

    例如,在搜索帖子的论坛或搜索产品页面时对在线商店进行分类时,CrawlSpider非常有用 .

    我们的想法是,您必须进入每个类别,搜索与您要提取的产品/项目信息相对应的链接 . 那些产品链接是在该示例的第二个规则中指定的链接(它表示在URL中具有 item.php 的那些) .

    现在蜘蛛如何继续访问链接,直到找到包含 item.php 的链接?这是第一个规则 . 它说访问包含 category.php 而不是 subsection.php 的每个链接,这意味着它不会从这些链接中精确提取任何"item",但它定义了蜘蛛的路径以找到真实的项目 .

    's why you see it doesn' t在规则中包含 callback 方法,因为它不会返回该链接响应供您处理,因为它将被直接跟随 .

相关问题