「基礎からはじめるPython 第3回 スクレイピングにチャレンジ!」にチャレンジ! その1

ITpro 連載「基礎からはじめるPython」の第3回「スクレイピングにチャレンジ!」にチャレンジ してみた。

手順

  1. Beautiful Soup をインストール
  2. 動作確認

1. Beautiful Soup をインストール

BeautifulSoupは,ファイル1個のライブラリなので,site-packagesに配置すればインストールは完了です。

第3回 スクレイピングにチャレンジ! | 日経 xTECH(クロステック)

とゆーことで、Beautiful Soup 公式サイト から BeautifulSoup.py をダウンロードし、site-packages(/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages)へコピー。

iPythonを起動してimport BeautifulSoupとタイプし,エラーが表示されなければOKです。

同上

オッケーでーす。

2. 動作確認

とりあえず掲載されているコードをそのまま iPython シェルに入力してみます。

import urllib
import BeautifulSoup

url = 'http://mixi.jp'
soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))

for _a in soup.findAll('a'):
    print _a.get('href')
第3回 スクレイピングにチャレンジ!(2ページ目) | 日経 xTECH(クロステック)

すると、

http://mixi.jp/
home.pl
about.pl
regist.pl
help.pl
/loginjack_redirector.pl?id=121
/loginjack_redirector.pl?id=122
/loginjack_redirector.pl?id=123
http://mixi.jp/remind_password.pl
https://mixi.jp/
http://mixi.jp/regist.pl
http://mixi.jp/home.pl
http://mixi.jp/about.pl
http://mixi.jp/regist.pl
http://mixi.jp/help.pl
http://mixi.co.jp/
http://mixi.jp/rules.pl
http://mixi.jp/privacy.pl
http://mixi.jp/help2.pl
http://mixi.jp/contact.pl?ad
http://mixi.jp/job.pl

できたー。HTML の出力も同じく OK です。

soupインスタンスを生成した時点で,BeautifulSoupによってすでにHTMLはUnicodeに変換されています。リスト1の8,9行目のfor文を削除し以下のメソッドにすると,インデントによって構造化されたHTMLが表示されます。

print soup.prettify()
同上

つづく。

参考

findAll() - BeautifulSoup

The findAll method traverses the tree, starting at the given point, and finds all the Tag and NavigableString objects that match the criteria you give. The signature for the findall method is this:

findAll(name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)

These arguments show up over and over again throughout the Beautiful Soup API. The most important arguments are name and the keyword arguments.

The basic find method: findAll(name, attrs, recursive, text, limit, **kwargs) - Beautiful Soup documentation
prettify() - BeautifulSoup

You can turn a Beautiful Soup document (or any subset of it) into a string with the str function, or the prettify or renderContents methods. You can also use the unicode function to get the whole document as a Unicode string.

The prettify method adds strategic newlines and spacing to make the structure of the document obvious. It also strips out text nodes that contain only whitespace, which might change the meaning of an XML document.
The str and unicode functions don't strip out text nodes that contain only whitespace, and they don't add any whitespace between nodes either.

Printing a Document - Beautiful Soup documentation
urlopen - urllib

urlopen( url[, data[, proxies]])
URL で表されるネットワーク上のオブジェクトを読み込み用に開きます。 (略)接続を作ることができないか、サーバがエラーコードを返した場合、 例外 IOError が送出されます。全ての処理がうまくいけば、 ファイル類似のオブジェクトが返されます。このオブジェクトは以下の メソッド: read() 、 readline() 、 readlines() 、 fileno() 、 close() 、 info() そして geturl() をサポートします。

http://www.python.jp/doc/nightly/lib/module-urllib.html