$ docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b1ff5faed1ca scrapinghub/splash "python3 /app/bin/sp…" 3 hours ago Up 3 hours 0.0.0.0:5023->5023/tcp, 0.0.0.0:8050-8051->8050-8051/tcp amazing_zhukovsky
次はscrapy_splashをインストールします。
$ sudo pip install scrapy_splash
これで必要なものがインストールできました。
Javascriptで動的に生成されるページ
Scapye内でSplashを使用する場合、基本的には下記の順序で行います。
scrapy_splashライブラリをインストール
Splashのサーバーを起動する(Dockerコンテナ)
settings.pyに必要な情報を記載する
SpiderでRequestクラスではなく、SplashRequestクラスを利用する。
Luaスクリプトでブラウザを操作する
ここでは、偉人の名言サイト"Quotes To Scrape"のJavaScript版ページを対象にします。このサイトは、Webページ内にJavaScriptが仕込まれており、生のHTMLには名言は含まれていません。Webブラウザでページがレンダリングされたときに。JSON形式のデータオブジェクトを反復処理してDOMを作成することで、サイトに名言のブロックが作られる仕様になっています。そのため、Scrapyでそのままデータを抽出することはできません。
<script src="/static/jquery.js"></script>
<script>
var data = [
{
"tags": [
"change",
"deep-thoughts",
"thinking",
"world"
],
"author": {
"name": "Albert Einstein",
"goodreads_link": "/author/show/9810.Albert_Einstein",
"slug": "Albert-Einstein"
},
"text": "\u201cThe world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.\u201d"
},
【略】
{
"tags": [
"humor",
"obvious",
"simile"
],
"author": {
"name": "Steve Martin",
"goodreads_link": "/author/show/7103.Steve_Martin",
"slug": "Steve-Martin"
},
"text": "\u201cA day without sunshine is like, you know, night.\u201d"
}
];
for (var i in data) {
var d = data[i];
var tags = $.map(d['tags'], function(t) {
return "<a class='tag'>" + t + "</a>";
}).join(" ");
document.write("<div class='quote'><span class='text'>" + d['text'] + "</span><span>by <small class='author'>" + d['author']['name'] + "</small></span><div class='tags'>Tags: " + tags + "</div></div>");
}
</script>
➜ cat item_js.json
[
{"author": "Albert Einstein", "quote": "\u201cThe world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.\u201d"},
{"author": "J.K. Rowling", "quote": "\u201cIt is our choices, Harry, that show what we truly are, far more than our abilities.\u201d"},
【略】
{"author": "Dr. Seuss", "quote": "\u201cA person's a person, no matter how small.\u201d"},
{"author": "George R.R. Martin", "quote": "\u201c... a mind needs books as a sword needs a whetstone, if it is to keep its edge.\u201d"}
]