LoginSignup
4
3

More than 5 years have passed since last update.

[機械学習で推奨タグ付け #1] はてなブログの記事のスクレイピング

Last updated at Posted at 2015-11-24

Hi, this is Bython Chogo. I have to learn English so I try to post article both English and Japanese :(

Now studying Machine Learning and practicing test scripting with Bayesian filtering. my plan is to estimate tag from web posted contents after learning several posts and tags.
Bayesian sample script can be got from Gihyo web page, I'll introduce later, before that today's topic and problem to talk is scraping contents from post.

I found good slide to describe what I'd like to say however I've lost ... orz. Will add it later.
Regarding the article, there is two way to scrape body contents. One is using characterized format of each contents. I don't need header or footer date for learning words because it may not useful for identifying the tag.

As a example, I try to scrape only article on Hatena Blog, the article is between the below tags.

    <div class=entry-contents>
    CONTENTS to SCRAPE!
    </div>

this case, I wrote below code.

    soup = BeautifulSoup( html, "lxml" )
    soup.originalEnoding
    tag = soup.find("div", {"class": "entry-content"})
    text = ""
    for con in tag.contents:
        p = re.compile(r'<.*?>')
        text += p.sub('', con.encode('utf8'))

Looks not cool.. but it works :(
Also I have to prepare all format I will scrape. This is very tired. So second way is to use learning method! But this looks difficult for me.

To be continued...

どうも梅村長後と申します。よろしくお願いいたします。英語の学習も兼ねているので英語と日本語で書いていますが、英語の不細工さには目をつむっていただければと思います。
現在機械学習のお勉強をしておりまして、その実践経験の一環でベイジアンを使った記事に対する自動タグ付けシステムを製作中です。ただ行うにあたって新たに覚えることが多く、千里の道も一歩からといったところで、こつこつとおこなっている次第でございます。

で、本日のお題は学習や判定に使う記事の抜出し、いわゆるScrapingってやつです。こいつもいまホットなテーマでいろいろなところで記事をみつけることができます。先日そうやって探した良記事があったのですが、うっかりしたことに失念してしまいました。あとで張りなおしたいと思います。
で、その記事の内容は対象ページのヘッダとかフッタとかを無視して、記事の本文のみを抽出する方法を2つ紹介していました。

一つはかくサイトのフォーマットに合わせてこつこつと記事本文の囲みタグを登録して抜き出すこと。例えばはてなブログの場合はいかになります。

    <div class=entry-contents>
    CONTENTS to SCRAPE!
    </div>

で、こいつから中身を抽出するために以下のスクリプトを書いてみました。

    soup = BeautifulSoup( html, "lxml" )
    soup.originalEnoding
    tag = soup.find("div", {"class": "entry-content"})
    text = ""
    for con in tag.contents:
        p = re.compile(r'<.*?>')
        text += p.sub('', con.encode('utf8'))

たぶん、コードも不細工だろうなとおもいつつこれが精いっぱいです。
で、この方法だと各サイトの特徴的な囲みを登録しなくてはいけない、それが面倒な場合に2つ目の方法の学習を使う、と前述の記事にはかかれていたような気がします。ただ、現時点での実力ではなかかな難しいところです。

このスクリプトについては完成までシリーズ化していきたいと思います。

4
3
2

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
4
3