2017-06-13 56 views
1

所以我試圖用CrawlSpider並瞭解Scrapy Docs下面的例子:Scrapy - 瞭解CrawlSpider和LinkExtractor

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方法提取信息。但是,第一條規則的目的究竟是什麼?它只是說它「收集」鏈接。這意味着什麼?如果他們沒有從中提取任何數據,爲什麼它有用?

回答

3

CrawlSpider在抓取論壇搜索帖子或在搜索產品頁面時對網上商店進行分類時非常有用。

這個想法是,「不知何故」你必須進入每個類別,搜索鏈接,對應於你想要提取的產品/物品信息。這些產品鏈接是在該示例的第二條規則中指定的鏈接(它表示在url中有item.php的鏈接)。

現在蜘蛛應該如何繼續訪問鏈接,直到找到那些包含item.php的鏈接?這是第一個規則。它說要訪問每個包含category.php而不是subsection.php的鏈接,這意味着它不會從這些鏈接中精確提取任何「項目」,但它會定義蜘蛛的路徑以查找真實項目。

這就是爲什麼你看到它在規則中不包含callback方法,因爲它不會返回該鏈接響應供您處理,因爲它會被直接跟蹤。

+0

啊,我明白了......所以這個蜘蛛會從像example.com/category.php/item.php這樣的鏈接中提取數據,但不會從像example.com/subsection這樣的鏈接中提取數據。 PHP/item.php'? – ocean800

+1

是的,如果你的意思是提取'example.com/subsection.php/item.php',它首先需要訪問'example.com/subsection.php'頁面。假設你在'example.com'(主頁)並且在那個頁面裏它只有2個鏈接(在body內部):'example.com/category.php'和'example.com/subsection.php',以及當你訪問他們時,你可以找到產品網址(使用'item.php')。然後,蜘蛛只會提取'category.php'裏面的那些,因爲它永遠不會訪問'subsection.php'。 – eLRuLL

+0

我明白了......謝謝!那麼如果有人可以說,還有第三個鏈接'example.com/third.php/item.php',但我有與上面相同的規則,它會解析這些鏈接嗎?只是混淆了行爲,因爲'third.php'既不在'allow =()'或'deny =()'中。你是否必須手動拒絕所有可能的額外鏈接? – ocean800