【Scrapy】簡単なScrapyを作ってみよう2/2 〜Crawlingスクリプトの作成〜
今回の章
セクション3:Building Basic Spider withScrapy
10. Scrapy Simple Spider - Part 3
目次
①Scrapyの中にspiderの作成
②結果の確認
①Scrapyの中にspider(quotes.py)の作成
import scrapy
class QuotesSpider(scrapy.Spider):
name = 'quotes'
allowed_domains = ['quotes.toscrape.com']
start_urls = ['http://quotes.toscrape.com/']def parse(self, response):
h1_tag = response.xpath('//h1/a/text()').extract()
tags = response.xpath('//*[@class="tag-item"]/a/text()').extract()
yield {'H1 Tag': h1_tag,'Tags': tags}
1.def関数で指定する文字の取得
基本的なことだがクラスはdef関数をまとめるもの!
2.yield分で宣言する
これも基本だがyieldはreturnのようなもの。yieldは関数一旦終了でreturnは終了するのメモリの消費量を抑えることが出来る。
3. 辞書型に格納する
②結果の確認
scrapy crawl (spider名)で実行できる。
(venv_20201101) MacY:quotes_spider macbookproy$ scrapy crawl quotes
結果は以下の通り
以下の部分でしっかり辞書型に格納できていることがわかる。
2020-11-01 16:26:21 [scrapy.core.scraper] DEBUG: Scraped from <200 http://quotes.toscrape.com/>
{'H1 Tag': ['Quotes to Scrape'], 'Tags': ['love', 'inspirational', 'life', 'humor', 'books', 'reading', 'friendship', 'friends', 'truth', 'simile']}
2020-11-01 16:26:21 [scrapy.core.engine] INFO: Closing spider (finished)
robots.txtのみ404になっているが、他は取得できているのが確認できる。