Google Analytics API を Perl で使ってみる

Google Analytics API を Perl で使ってみる #

世間から五周回遅れくらいで、Google Analytics の API を使ってみるよ

実際使う分には JavaScript で、Developer’s Guide にある通りにやればいいんだけど、Perl のサンプルがなくて寂しいので、書いてみた

Net::Google::AuthSub とか使えば、前半部分はもっと簡単になりますな

#!/usr/bin/perl

use strict;
use warnings;

use LWP::UserAgent;
use XML::FeedPP;

my $email = 'your_analytics_id';
my $pass = 'your_analytics_pw';
my $ids = 'profile_id';

my $ua = LWP::UserAgent->new;
$ua->env_proxy;

# get token
my $auth = $ua->post('https://www.google.com/accounts/ClientLogin',
                    {
                     Email => $email,
                     Passwd => $pass,
                     service => 'analytics',
                     source => 'LWP-UserAgent',
                     accountType => 'HOSTED_OR_GOOGLE'
                    }
                   );
die 'auth:'.$auth->status_line unless $auth->is_success;
my ($token) = $auth->content =~ /Auth=(.*)/;

# get result (atom)
my $url = 'https://www.google.com/analytics/feeds/data?'
    .'ids=ga:'.$ids
    .'&dimensions=ga:requestUri'
    .'&metrics=ga:pageviews'
    .'&sort=-ga:pageviews'
    .'&start-date=2009-04-01'
    .'&end-date=2009-04-30'
    .'&max-results=5';
my $req = HTTP::Request->new( GET => $url );
$req->header('Authorization' => 'GoogleLogin auth='.$token);
$req->content_type('application/atom+xml');
my $res = $ua->request( $req );
die 'data:'.$res->status_line unless $res->is_success;

# parse atom data
my $feed = XML::FeedPP->new( $res->content );
for my $item ( $feed->get_item() ) {
    print $item->{'dxp:dimension'}->{'-value'},':',$item->{'dxp:metric'}->{'-value'},"\
";
}

See Also

Copyright © 髭。/ Hugo + hugo-book