こんばんは
本日2つ目のブログでございます。
この記事では技術系のことについて私が忘れないように最近使ってるScrapyについて使い方を記録しておきたい。
Scrapy
ScrapyとはWebページをダウンロードしてきてパースを行ういわゆるスクレイピングを行うフレームワークである。
試しにPython2系であるページの情報を取得することにしてみた。
とりあえずインストール
$ pip install scrapy
それからあたらしいプロジェクトを作る
$ scrapy startproject testscrapy $ tree testscrapy testscrapy/ ├── scrapy.cfg └── testscrapy ├── __init__.py ├── __init__.pyc ├── items.py ├── items.pyc ├── pipelines.py ├── settings.py ├── settings.pyc └── spiders ├── __init__.py ├── __init__.pyc ├── testspider.py └── testspider.pyc
次にitems.pyを編集する。ここは自分なりにページから取得してくる情報をオブジェクトにして定義するものと理解している。
1 # -*- coding: utf-8 -*- 2 3 # Define here the models for your scraped items 4 # 5 # See documentation in: 6 # http://doc.scrapy.org/en/latest/topics/items.html 7 8 import scrapy 9 10 11 class TestscrapyItem(scrapy.Item): 12 # define the fields for your item here like: 13 # name = scrapy.Field() 14 title = scrapy.Field() 15 url = scrapy.Field() 16 content = scrapy.Field()
ここでは
- title(ページのタイトル)
- url(ページのURL)
- content(ページの内容)
を取得するように定義
次に同じディレクトリのsettings.pyに
DOWNLOAD_DELAY=3 ROBOTSTXT_OBEY=True
を追加する。
次にtestscrapy/testscrapy/spidersにtestspider.pyを作る。
$ scrapy genspider testspider [domain]
上記のコマンドでtestspider.pyの雛形を作成することができる。
1 # -*- coding: utf-8 -*- 2 import scrapy 3 4 5 class TestspiderSpider(scrapy.Spider): 6 name = "testspider" 7 allowed_domains = [[domain]] 8 start_urls = ( 9 'http://[domain]', 10 ) 11 12 def parse(self, response): 13 pass
start_urlsに設定したURLのページをスクレイピングすることとなる。次のコマンドでクロールを行う。
$ scrapy crawl testspider
次回のブログあたりで実例を書いていこうと思う。今日はつかれた.....