LoginSignup
0
3

More than 5 years have passed since last update.

【Scrapy】ミニマムサンプル

Posted at

Scrapyとは、クローリングとスクレイピングを行うフレームワーク
プロジェクト単位で複数のSpiderと関連するクラスをまとめて管理する

ドキュメント
https://docs.scrapy.org/en/latest/

準備

startproject

プロジェクトをつくる

scrapy startproject <project_name> [project_dir]

genspider

spiders/に移動し、Spiderをつくる

scrapy genspider [-t template] <name> <domain>

Spiderとは、クロールの実行方法、データの抽出方法など、サイトをスクレイピングする際のカスタム動作を定義したもの。
https://doc.scrapy.org/en/latest/topics/spiders.html

サンプル

ミニマムなサンプル。
ICS MEDIAの最新の記事を取得するだけ。

ics.py
# -*- coding: utf-8 -*-
import scrapy


class IcsSpider(scrapy.Spider):
    # Spiderを実行する際に呼び出す名前 ex. scrapy crawl ics
    # 必ずユニークであること
    name = 'ics'
    allowed_domains = ['ics.media']

    # クローリングのエントリポイント
    start_urls = ['https://ics.media/']

    def parse(self, response):
        for article in response.css('#app-articles > .row > div'):
            yield {
                "url": article.css('a.thumb::attr(href)').extract_first(),
                "title": article.css('.entryTitle a::text').extract_first()
            }

保存

-oのオプションでJSON形式で保存する。

scrapy crawl ics -o ics.json

ics.json
[
    {
        "title": "上下中央揃えのCSSまとめ。Flexboxがたった3行で最も手軽", 
        "url": "https://ics.media/entry/17522"
    }, 
    {
        "title": "サンプルで理解するWebGL 2.0 – Transform Feedbackによるパーティクル表現", 
        "url": "https://ics.media/entry/17505"
    }, 
...
]

セレクタ

.extract_first()で最初の要素を抽出している。
https://doc.scrapy.org/en/latest/topics/selectors.html

参考
scrapyでよく使うxpath, cssのセレクタ

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3