Drkcore

04 06 2011 perl javascript Tweet

WWW::Mechanize::FirefoxとWeb::QueryでAjaxのサイトをスクレイピングする

第1回 静岡ITPro勉強会 インフラ部で発表してきた。デモが動かなかったのは、名前がダサいという理由で電車の中でhtmlのファイル名を変えたせいでした、アホ過ぎる。

ま、こんな感じのファイルを用意します。AjaxでATNDのAPIにアクセスして今日の参加者を表示するっていうやつです。

<!DOCTYPE html>
<html>
<head>
<title>ajaxtest</title>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
</head>

<body>
<button id=ajax name="atnd">クリックするとユーザー一覧を表示します</button>
<div class=users></div>
<script>

$("button#ajax").click(function(){
$.getJSON('http://api.atnd.org/events/users/?event_id=16076&format=jsonp&callback=?',
function(data){
 var items = [];

 $.each(data.events[0].users, function() {
   items.push('<li>' + this.nickname + '</li>');
 });

 $('<ul/>', {
   'class': 'userlist',
   html: items.join('')
 }).appendTo('div.users');
});
});
</script>
</body>
</html>

これをスクレイピングするにはWWW::Mechanize::Firefoxを使って

use WWW::Mechanize::Firefox;
use Web::Query;
use Encode;

my $mech = WWW::Mechanize::Firefox->new();
$mech->get('http://localhost:8000/');
$mech->click({ xpath => '//button[@name="atnd"]', synchronize => 0 });
sleep(2);
#print $mech->content;

my $q = Web::Query->new_from_html($mech->content);
$q->find('li')->each(sub {
                my $i = shift;
                printf "(%d) %s\n", $i+1, encode('utf-8', $_->text);
              });

実行するとこんな風に出力されるはずです。

(1) secondarykey
(2) ando_ando_ando
(3) となか
(4) yukio.47
(5) Kaz110
(6) tatsuya.ueda
(7) taji_314159265
(8) kzfm
(9) non

凡ミスでここまでは行かなかった。カナシス

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021