所以我試圖用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
方法提取信息。但是,第一條規則的目的究竟是什麼?它只是說它「收集」鏈接。這意味着什麼?如果他們沒有從中提取任何數據,爲什麼它有用?
啊,我明白了......所以這個蜘蛛會從像example.com/category.php/item.php這樣的鏈接中提取數據,但不會從像example.com/subsection這樣的鏈接中提取數據。 PHP/item.php'? – ocean800
是的,如果你的意思是提取'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
我明白了......謝謝!那麼如果有人可以說,還有第三個鏈接'example.com/third.php/item.php',但我有與上面相同的規則,它會解析這些鏈接嗎?只是混淆了行爲,因爲'third.php'既不在'allow =()'或'deny =()'中。你是否必須手動拒絕所有可能的額外鏈接? – ocean800