2010年9月19日日曜日

BeautifulSoup - Python HTML/XMLパーサの導入

導入方法
1.ここからBeautifulSoup.pyをダウンロード
2.作業フォルダ or C:\cygwin\lib\python2.6に配置(前提:Cygwin環境)

使用例
Googleのページを取ってきて表示
>>> from BeautifulSoup import BeautifulSoup
>>> from urllib import urlopen
>>> soup=BeautifulSoup(urlopen('http://www.google.co.jp/'))
>>> soup.prettify()
<!doctype html>\n<html>\n <head>\n <meta http-equiv="content-type" content="text/html; charset=utf-8" />\n <title>\n Google\n </title>
・・・
タイトルタグを取得して表示
>>> soup.head.title
<title>Google</title>
<a>タグを取得して、一番目を表示
>>> links=soup('a')
>>> links[0]
<a onclick="gbar.qs(this)" href="http://www.google.co.jp/imghp?hl=ja&tab=wi" class="gb1">画像</a>
一番目の<a>タグのhref属性に記載されたリンク先urlと,<a>タグのテキストコンテンツを表示
>>> links[0].get('href')
u'http://www.google.co.jp/imghp?hl=ja&tab=wi'
>>> links[0].contents[0]
u'\u753b\u50cf'

詳しい使用方法はここ