Published Date : 2020年9月5日6:34

【python, Web Scraping】scrapyでウェブスクレイピング: パート2 ~ Spiders ~
Web scraping with scrapy: Part 2 ~ Spiders ~


This blog has an English translation


YouTubeにアップした動画、「【python, Web Scraping】scrapyでウェブスクレイピング: パート2 ~ Spiders ~」の補足説明の記事です。

Here's a little more about the 「【python, Web Scraping】Web scraping with scrapy: Part 2 ~ Spiders ~」 video I uploaded to YouTube.


目次

Table of Contents




① 動画の説明
① Video Description



scrapyを使ってウェブスクレイピングをします。

This time, we'll use the third party python module, scrapy, to do web scraping.

パート2では前回のスクリプトを繋げて、Scrapyのプロジェクトを作成します。

In Part 2, we combine the previous scripts into a single Scrapy project.

まず、適当なフォルダを作ってください。

First, please make a suitable folder somewhere.

mkdir newdir
cd newdir

Scrapyのプロジェクトを作成するコマンドを入力します。

Enter the command to create a Scrapy project.

scrapy startproject [your scrapy project]
cd [your scrapy project
scrapy genspider example example.com

spidersというフォルダを開くと、先ほど指定した名前のファイルができています。

If you open the folder for the project you created and then open the folder called spiders, a file with the name you specified earlier is created.

nameはスパイダーの名前です。クローラーを実行するファイル名はこの名前と一致している必要があります。

name is the name of the spider. The file name to run the crawler must match this name.

allowed_domainsはこのドメイン名からしか情報をとってきませんよという意味です。

[allowed_domains] means it will only get information from this domain name.

start_urlsはコンテンツをとってくる起点となるURLです。

start_urls is the starting URL for retrieving content from the Web. That is, the crawl is initiated from this URL.

start_urlsはこのように複数のURLを指定することもできます。

As you can see, start_urls can specify multiple URLs.

とりあえず動作確認をするため、

For now, in order to check the operation,

ブログのタイトルを表示させるだけにして実行しましょう。

To get started, just run a script that displays the title of your blog to see how it works.

コマンドプロンプトに[scrapy list]と入力します。

Type [scrapy list] at the command prompt.

scrapy list

正常通りなら実行ファイルの名前が表示されます。

If successful, the name of the executable is displayed.

example

この名前を使用して以下のコマンドを打ちます。

Using this name, type the following command.

scrapy crawl example

すると沢山文字が表示された中にタイトルが表示されています。

Then, the title is displayed among many characters.

動作を確認したのでクローラーを作成しましょう。

Let's create a crawler now that we have confirmed its operation.

コンテンツをJSONなどで保存できるように、まずはitems.pyを編集します。

To save crawled content to JSON, etc., edit [items.py].

開くとあらかじめクラスが記述されています。

The class is already written when you open it.

今回は簡単なデモなので、titleとブログ記事のみ収集します。

This is a simple demo, so I will only collect title and blog posts.

titleやarticle等の変数名は辞書でいうキーになります。

The name of a variable, such as title or article, is a dictionary key.

ではexample.pyを書いていきましょう。

Now let's write example.py.

まずはitemsクラスをインポートします。

First import the items class.

parseメソッドはデフォルトで最初のレスポンスの時に実行される関数です。

The parse method is the function that is executed by default on the first response.

[scrapy.Request()]の引数[dont_filter=True]の説明をします。

Describes the arguments [dont_filter = True] for [scrapy.Request()].

Scrapyはデフォルトでは同じURLにアクセスすることができないようになっています。

Scrapy does not allow access to the same URL by default.

試しに[item.py]に[page_url]を一時的に加えてから、

Try temporarily add [page_url] to [item.py],

[item = ScrapyTestItem()]の後に、

then add [item['page_url'] = response.url]

[item['page_url'] = response.url]を加えます。

after [item = ScrapyTestItem()].

response.urlから返される値は[start_urls]の最初の値だけです。

In this case, response.url only returns the first value of [start_urls].

ところがコールバック関数内ではページ毎のURLになっています。

However, in the callback function, the URL for each page is displayed.

つまり、For文の中でURLを変えてリクエストを行っても、

In other words, if you make a request with a different URL in the For statement,

同じ[http://127.0.0.1:8000/]にアクセスしていますので、

you are still accessing the same [http://127.0.0.1:8000/],

[dont_filter=True]にして、同じurlにアクセスしても大丈夫なようにしなければなりません。

so you need to set it to [dont_filter = True] so that it's okay to access the same url.

ブログサイトの構造はとても簡単で、

The structure of the blog site is very simple.

urlの[posts/number]の[number]をインクリメントしていけば、

you can get all the articles by incrementing

全ての記事を取得できるようになっています。

the [number] of the url [posts/number].

なので、urlの[posts/number]が存在するまで、ループさせて記事を取得していきます。

So I loop through the articles until the url's [posts/number] exists.

あらかじめ、ページの上限数を調べておくと、簡単な記述で済みます。

If you check the maximum number of pages beforehand, it is easy to write.

あとはコールバック関数を用意して、

All you need to do is provide a callback function

XPATHやCSSセレクタを使用して記事とタイトルを取得していくだけです。

and use the XPATH and CSS selectors to retrieve the article and title.

さて、これを保存してから最後の仕上げです。

Now, the last finish after saving this.

[settings.py]という設定ファイルを編集します。

Edit the configuration file named [settings.py].

必要な設定は二つだけです。

Only two settings are needed.

これは[robots.txt]に従うという意味です。

This means follow [robots.txt].

[robots.txt]とは取られたくない情報を、クロールされないように制限するファイルです。

[robots.txt] is a file that restricts information that you don't want to be captured from being crawled.

これがあるにも関わらず、

Set this to True

無理やりクロールしようとするのを避けるためにTrueにします。

to avoid forcing crawls when this exists.

ページの情報をダウンロードしたあとに、3秒間待つようにする設定です。

Wait 3 seconds after downloading the page information.

サーバーへの負担を軽くする為です。

This is to reduce the burden on the server.

後はお好きなようにコメントアウトしたりオプション機能を付け足してください。

Then, comment out or add optional functions as you like.

それでは[settings.py]を保存して、 クロールしていきましょう。

Now let's save [settings.py] and crawl the content.

scrapy crawl example -o example.json

成功すればこのようjsonファイルが出来上がります。

If you succeed, you will get this json file.

お疲れさまでした。アディオス。

Thank you for your hard work. Adios.



以上です。お疲れ様です。

That's all. Thank you for your hard work.