PerlでGoogle Analytics API

            <div class="section">

Google Analytics APIでデータを取得するプログラムをPerlで書いた。

といっても、たつをさんの「「Google Analytics API を Perl から扱うスクリプト」の標準モジュール使用版」からいただいたコードを少し変えただけです。

GoogleAnalytics.pm [perl] package GoogleAnalytics;

use strict; use warnings; use HTTP::Request::Common (); use LWP::UserAgent; use XML::Simple; use Data::Dumper;

=pod 参考 http://tnnsst35.me/2009/12/08/perl%E3%81%A7google-analytics-api/

  1. Specify the e-mail address to be used in the google analytics to $email.
  2. Specify password to be used in the google analytics to $pass.
  3. Set the domain of the target service to $source.
  4. Run the login function and ls function. login($email, $pass, $source); ls();
  5. Set the ga:profileId in the result to $profile_id. { 'value' => '11111111', 'name' => 'ga:profileId' } ex. $profile_id = 'ga:123456789'; // The prefix a ga:. =cut

my $profile_id = 'ga:11111111'; my $email = 'hoge@foo.jp'; my $pass = 'password'; my $source = 'bar.jp';

my $ua = LWP::UserAgent->new(); my $xs = XML::Simple->new( KeyAttr => [''], ForceArray => ['entry'] ); my ( $req, $res, $auth_key );

GoogleAnalytics認証

sub login { my ($email, $password, $source) = @_; my $auth_url = 'https://www.google.com/accounts/ClientLogin'; my $service = 'analytics'; $req = HTTP::Request::Common::POST( $auth_url, [ accountType => 'GOOGLE', Email => $email, Passwd => $password, service => $service, source => $source ] ); $res = $ua->request($req); die $res->status_line if $res->is_error; my $content = $res->content; if ( $res->content =~ /Auth=([^\s]+)/ ) { $auth_key = $1; } else { die "can't find auth key!"; } }

離脱率ワード取得

sub get_exit_word { login($email, $pass, $source);

my ($days, $min_pv) = @_;
if (!defined($days) || !defined($min_pv)) {
    ls();
}
my ($day,$mon,$year) = (localtime(time - 60 * 60 * 24 * $days))[3..5];
$year += 1900;
$mon += 1;
my $start_date = sprintf('%04s-%02s-%02s', $year, $mon, $day);
($day,$mon,$year) = (localtime(time))[3..5];
$year += 1900;
$mon += 1;
my $end_date = sprintf('%04s-%02s-%02s', $year, $mon, $day);
my $dimensions = 'ga:searchKeyword';
my $metrics = 'ga:searchExits,ga:searchUniques';
my $filters = "ga:searchUniques%3E%3D$min_pv";
my $ref = analytic($start_date, $end_date, $dimensions, $metrics, $filters);
return $ref;

}

GoogleAnalytics APIをたたく

sub analytic { my ($start_date, $end_date, $dimensions, $metrics, $filters) = @_; my $args = shift; my $feed_url = 'https://www.google.com/analytics/feeds/data'; my $profile_id = $profile_id; $feed_url = "$feed_url?ids=$profile_id&metrics=$metrics". "&dimensions=$dimensions". "&start-date=$start_date&end-date=$end_date". "&filters=$filters". "&prettyprint=true"; #xxx $res = $ua->request( HTTP::Request::Common::GET( $feed_url, 'Authorization' => "GoogleLogin Auth=$auth_key" ) ); my $ref = $xs->XMLin( $res->content ); return $ref->{'entry'}; }

ユーザ情報を調べる

sub ls { $res = $ua->request( HTTP::Request::Common::GET( 'https://www.google.com/analytics/feeds/accounts/default?prettyprint=true', 'Authorization' => "GoogleLogin Auth=$auth_key" ) );

my $ref = $xs->XMLin( $res->content );
print Dumper($ref), "\n";

}

1; [/perl]

loginで認証して、analyticでデータを取得するだけです。

analyticの中にある$feed_urlのパラメータをいじることで、いろいろなデータを取得できます。パラメータについてはコチラ

特に、dimensionsとmetricsは取得するデータの種類を指定することができます。dimensionsとmetricsについてはコチラ

取得したデータをいろいろ加工するだけなら、コレで十分っぽいです。

参考

http://chalow.net/2009-10-21-3.html
http://code.google.com/intl/ja/apis/analytics/docs/gdata/gdataReferenceDimensionsMetrics.html
http://code.google.com/intl/ja/apis/analytics/docs/gda/gdataReferenceDataFeed.html