だから私は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のホームページ、カテゴリリンクの収集、およびitem linkを、parse_itemメソッドで解析します。各アイテムのレスポンスでは、XPathを使用してHTMLからいくつかのデータが抽出され、アイテムがそのアイテムで満たされます。
2番目のルールでは、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'(ホームページ)にあり、そのページの内部に' example.com/category.php'と 'example.com/subsection.php'という2つのリンクしかないとしましょうあなたがそれらにアクセスすると、商品のURLを見つけることができます( 'item.php'で)。それで、 'subsection.php'を訪れたことがないので、クモは' category.php'の中のものだけを抽出します。 – eLRuLL
私は見る...ありがとう!だから、もし第三者のリンク 'example.com/third.php/item.php'もあったとしますが、私は上記と同じルールを持っていました。これらのリンクを解析するでしょうか? 'third.php'は' allow =() 'と' deny =() 'のどちらにもないので、動作を混乱させるだけです。可能なすべての追加リンクを手動で拒否する必要がありますか? – ocean800