しばらくベンチマークコードを書いてなくてすっかり忘れていたので、メモ書きです。今回は例題として、yahooのこのページをBeautifulSoupとlxmlでのスクレイピング比較をしてみる事にしました。比較対象の関数は以下の通りです。どちらのコードも入力・出力ともに同じなので、どちらが実行時間やメモリ使用量が少ないのかを知りたくなりますね。
# BeautifulSoup def scrape_with_bs(html): from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(html) rows = soup.find('table', attrs={'class':'channel9'}).findAll('tr') channels = rows[0].findAll('td', attrs={'class':'station'}) programs = rows[1].findAll('td', attrs={'class':'turnup'}) res = [] for ch, prog in zip(channels, programs): res.append((ch.find('span').string, ch.find('a').string, prog.find('a').string)) return res # lxml def scrape_with_lxml(html): import lxml.html root = lxml.html.fromstring(html.decode('utf-8')) rows = root.xpath('//table[@class="channel9"]/tr') channels = rows[0].xpath('td[@class="station"]') programs = rows[1].xpath('td[@class="turnup"]') res = [] for ch, prog in zip(channels, programs): res.append((ch.xpath('span/text()')[0], \ ch.xpath('descendant::a/text()')[0], \ prog.xpath('descendant::a/text()')[0]) ) return res
ちなみに上記の関数から得られる配列をprettyprintすると、以下の様な出力が得られます。各チャンネルごとに、今放送中の番組を取得しています。
[ [ "アナログ1ch", "NHK総合", "ニュース" ], [ "アナログ3ch", "NHK教育", "ハーバード白熱教室@東京大学「イチローの年俸は..." ], [ "アナログ4ch", "日本テレビ", "真相報道 バンキシャ!" ], [ "アナログ6ch", "TBS", "THE世界遺産「皇帝たちの地下宮殿」〜..." ], [ "アナログ8ch", "フジテレビ", "笑顔がごちそう ウチゴハン" ], [ "アナログ10ch", "テレビ朝日", "ドライブ A GO!GO!「群馬格安温..." ], [ "アナログ12ch", "テレビ東京", "TOKYO ..." ], [ "アナログ14ch", "TOKYO MX", "芸術史と芸術理論( 10)第1回◇放送..." ] ]

