scrapy で localhost サーバーのリソースをスクレイピングして parse 結果を json ファイルに出力する

他人のサーバーでテストすることは憚られる

環境

  • Mac OSX - 10.13.4
  • Python - 3.6.5
  • nginx - 1.12.2
  • scrapy - 1.5.0

localhost サーバー

workspace ディレクトリ直下の index.html を改変しておく。

/path/to/nginx/workspace/index.html

<html>
  <head>
    <style type="text/css">
      #caption {
        color: red;
      }   
      .elem {
        color: blue;
      }   
    </style>
  </head>
  <body>
    <h1 id="caption">hello world</h1>
    <div>
      <ul>
        <li class="elem">abc</li>
        <li class="electric">def</li>
        <li class="elem"><a href="#">link to myself</a></li>
      </ul>
    </div>
  </body>
</html>
$ nginx

クローラー

仮想環境で scrapy を導入

$ mkdir testdir && cd testdir
$ python3 -m venv ./venv/environment
$ source ./source/venv/environment/bin/activate
$ pip3 install scrapy
$ touch main.py

main.py

クローラー本体

import scrapy

class Spider(scrapy.Spider):
  start_urls = ['http://localhost:8080/index.html']
  name = 'spider'

  def parse(self, response):
    for text in response.xpath('//h1/text()').extract():
      yield { 'h1-text' : text }

    for dom in response.css('li.electric').extract():
      yield { 'dom li-electric' : dom }

    for text in response.xpath('//li/a/text()').extract():
      yield { 'text of a in li' : text }

クロール

$ scrapy runspider main.py -o outfile.json

クロール結果

outfile.json

[
{"h1-text": "hello world"},
{"dom li-electric": "<li class=\"electric\">def</li>"},
{"text of a in li": "link to myself"}
]

参考文献