Scrapy Simple Spider - Section 3

スクレーピーを設定する。

$ python3 -m venv venv_0512
$ source venv_0512/bin/activate
$ cd venv_0512
$ pip install scrapy
$ sudo pip install ipython

スクレーピーをの状況を確認する。

Yuki$ scrapy
Scrapy 1.5.0 - no active project

Usage:
  scrapy <command> [options] [args]

Available commands:
  bench         Run quick benchmark test
  fetch         Fetch a URL using the Scrapy downloader
  genspider     Generate new spider using pre-defined templates
  runspider     Run a self-contained spider (without creating a project)
  settings      Get settings values
  shell         Interactive scraping console
  startproject  Create new project
  version       Print Scrapy version
  view          Open URL in browser, as seen by Scrapy

  [ more ]      More commands available when run from project directory

Use "scrapy <command> -h" to see more info about a command

no active project が確認できる。

$ scrapy
Scrapy 1.5.0 - project: quotes_spider

Usage:
  scrapy <command> [options] [args]

Available commands:
  bench         Run quick benchmark test
  check         Check spider contracts
  crawl         Run a spider
  edit          Edit spider
  fetch         Fetch a URL using the Scrapy downloader
  genspider     Generate new spider using pre-defined templates
  list          List available spiders
  parse         Parse URL (using its spider) and print the results
  runspider     Run a self-contained spider (without creating a project)
  settings      Get settings values
  shell         Interactive scraping console
  startproject  Create new project
  version       Print Scrapy version
  view          Open URL in browser, as seen by Scrapy

Use "scrapy <command> -h" to see more info about a command

no active project が無くなっているのを確認できる。

次にプロジェクトを進める。

Usage:
  scrapy <command> [options] [args]

なので、ターミナルに 最初: scrapy
テンプレ作れという命令: genspider
URL: quotes http://quotes.toscrape.com/

$ cd quotes
$ scrapy genspider quotes http://quotes.toscrape.com/
Created spider 'quotes' using template 'basic' in module:
  quotes_spider.spiders.quotes

そうすると以下のスクリプトが出来る f:id:yukking3:20180512143810p:plain f:id:yukking3:20180512143842p:plain

$ scrapy  shell 

In [1]: fetch('http://quotes.toscrape.com/')
2018-05-12 14:45:16 [scrapy.core.engine] INFO: Spider opened
2018-05-12 14:45:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/> (referer: None)

In [2]: response
Out[2]: <200 http://quotes.toscrape.com/>

実際にh1の文字を抽出してみると f:id:yukking3:20180512145424p:plain

In [2]: response
In [5]: response.xpath('//h1/a/text()').extract()
Out[5]: ['Quotes to Scrape']

Quotes to Scrapeのtop10のタグを取得する

f:id:yukking3:20180512151024p:plain ちゃんと取得できているか確認する

In [7]: len(response.xpath('//*[@class="tag-item"]'))
Out[7]: 10

1個目のタグを取得する

f:id:yukking3:20180512151956p:plain

最初にタグを取得できるかやって見る

In [10]: response.xpath('//*[@class="tags"]/a/text()').extract()
Out[10]: 
['change',
 'deep-thoughts',
 'thinking',
 'world',

次に1番目のタグのみを取得する

In [11]: response.xpath('//*[@class="tags"]/a/text()').extract_first()
Out[11]: 'change'

Spiderを作る

urlからのresponseオブジェクトなのでresponseになる f:id:yukking3:20180512153216p:plain

以下が完成形のコードである。

# -*- coding: utf-8 -*-
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_first()
        tags = response.xpath('//*[@class="tag-item"]/a/text()').extract()

        yield {'H1 Tag': h1_tag, 'Tags': tags}

ちなみに、yieldは反復して要素を取り出すことが出来る型である。
return文でそのまま値を返す関数と違い莫大な量の戻り値を小分けにして返すことが出来る。 少量ずつデータを返す事でメモリの消費量を抑えることが出来る。

実際に実行すると

$ scrapy crawl quotes


2018-05-12 15:54:38 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2018-05-12 15:54:38 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2018-05-12 15:54:39 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://quotes.toscrape.com/robots.txt> (referer: None)
2018-05-12 15:54:39 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/> (referer: None)
2018-05-12 15:54:39 [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']}

結果が取得できている。
robots.txtのみ404になっているが、他は取得できているのが確認できる。