Last-modified: 2012-05-14 (月) 02:17:24
Perl/WebスクレイピングにXPathを使いたい

概要

XPathを使用し、楽にWebスクレイピングを行ないます。


HTML::TreeBuilderを使用します。
デモでは、当サイト左カラムのメニュータイトル一覧を取得します。
(2010/10/28現在の構造をもとに取得します)

コード

Everything is expanded.Everything is shortened.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
-
!
 
 
 
 
 
 
 
 
 
-
!
-
!
-
!
 
-
!
-
!
 
 
 
 
-
!
 
-
-
!
-
!
-
!
|
|
-
|
!
|
-
!
!
 
-
-
!
!
 
#!/usr/bin/perl
 
use strict;
use warnings;
use encoding 'utf8';
binmode(STDERR, ':raw :encoding(utf8)');
 
use LWP::UserAgent;
use HTML::TreeBuilder;
use HTML::TreeBuilder::XPath;
 
################################################
 
# URL
my $url = 'http://vok.paburica.com/';
# ユーザーエージェント(適当)
my $user_agent = 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)';
 
################################################
 
# ユーザーエージェント設定
my $ua = LWP::UserAgent->new();
$ua->timeout(10);
$ua->agent($user_agent);
$ua->parse_head(0);
 
# ページ取得
my $response = $ua->get($url);
if ($response->is_success)
{
    # 成功
    my $tree = HTML::TreeBuilder::XPath->new();
    # パース
    $tree->parse($response->content);
    # XPathで絞り込む
    my @list = $tree->findvalues('//div[@id="left_column_menubar"]/h4');
    
    foreach my $val (@list)
    {
        print "$val\n";
    }
    
    # 後始末
    $tree->delete();
}
else
{
    # 失敗
    print "$response->status_line\n";
}

検証時の環境

参考