so tired

仮想化、ハードウェアなどの技術メモ

BeautifulSoupを試してみた

年末年始はpythonの勉強をしよう!ということで、BeautifulSoupでスクレイピングを試してみた。

インストールの準備

まずはBeautifulSoupを利用する環境を整える。
BeautifulSoupのインストールにeasy_installコマンドを利用するためsetuptoolsをインストールする。
インストーラをダウンロードして、実行。

# wget http://peak.telecommunity.com/dist/ez_setup.py
# python ez_setup.py

自分の環境では"zlib not available"のエラーが出て一発ではうまくいかなかった。

Downloading http://cheeseshop.python.org/packages/2.5/s/setuptools/setuptools-0.6c6-py2.5.egg
Traceback (most recent call last):
  File "ez_setup.py", line 226, in <module>
    main(sys.argv[1:])
  File "ez_setup.py", line 160, in main
    from setuptools.command.easy_install import main
zipimport.ZipImportError: can't decompress data; zlib not available

この場合、zlib-develをインストールして、pythonをインストールし直す。
自分の環境はpython2.7だったのでついでに2.7.1に入れ直した。

# yum install zlib-devel
# wget http://www.python.org/ftp/python/2.7.1/Python-2.7.1.tgz
# tar zxvf Python-2.7.1.tgz
# cd Python-2.7.1
# ./configure CFLAGS=-fPIC ./configure --enable-shared 
# make
# make install

インストール

無事setuptoolsがインストールできたらいよいよBeautifulSoupをインストールする。

# easy_install BeautifulSoup

いざ実行

いろいろ試しながらテレビ番組表をスクレイピングするコードを書いてみた。
情報取得元はyahooテレビ番組表のトップページにした。
ぱっと見て取りやすそうだったので。
[test.py]

  1 #!/usr/bin/python
  2 #-*- encoding: utf-8 -*-
  3 
  4 import logging, sys, urllib
  5 import BeautifulSoup
  6 
  7 url = 'http://tv.yahoo.co.jp'
  8 soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read())
  9 
 10 for detailsrc in soup.findAll("span", {"class":"detail"}):
 11     text = ""
 12     for timesrc in detailsrc.find("span", {"class":"time"}):
 13         texttime = timesrc.string
 14         print "====="
 15         print str(texttime)
 16     for asrc in detailsrc.find("a"):
 17         texta = asrc.string
 18         if texta is None:
 19             break
 20         text = str(text) + str(texta)
 21     print text

実行結果

# python test.py
=====
24:00
ニュース・気象情報
=====
23:50
SCOOPER
=====
23:20
世間に飛び出せ!バナナ藩
=====
24:00
JNNニュース
=====
24:00
もしもドラフト会議
=====
24:00
その後
=====
24:05
SABU SESSION「投稿動画で北島三郎とセッション!?」
=====
24:10
なりきり完コピ選手権
=====
24:18
NNNニュース&amp;スポーツ
=====
24:20
『ぷっ』すま年末スペシャル
=====
24:43
ハッピーMusic
=====
24:50
SONGS選「松任谷由実」

一応取れたけどどの番組が何chか全然わかりませんな。
構造的にテレビ局名を取得するのが難しかったのです。