Skip to content

Instantly share code, notes, and snippets.

@marcelnicolay
Created April 17, 2012 18:38
Show Gist options
  • Save marcelnicolay/2408078 to your computer and use it in GitHub Desktop.
Save marcelnicolay/2408078 to your computer and use it in GitHub Desktop.
Google Analytics - Most Visited
# coding: utf-8
import sys
import os
import httplib2
from gdata.analytics.client import DataFeedQuery, AnalyticsClient
from gdata.gauth import ClientLoginToken
from gdata.analytics.service import AccountsService
class GAClient(object):
def __init__(self, profile_ids, user, password, account_type, source):
self.profile_ids = profile_ids
self.user = user
self.password = password
self.account_type = account_type
self.source = source
self._client = None
def auth(self):
client = AccountsService()
client.ClientLogin(
self.user,
self.password,
account_type=self.account_type,
source=self.source)
token = client.GetClientLoginToken()
client_token = ClientLoginToken(token)
self._client = AnalyticsClient(client_token)
def get_client(self):
if not self._client:
self.auth()
return self._client
def get_data(self, query):
query['ids'] = ",".join(self.profile_ids)
client = self.get_client()
data_feed_query = DataFeedQuery(query)
return client.get_data_feed(data_feed_query)
def get_pages_most_visited(self, start_date, end_date, pattern, max_results=50):
query_params = {
'metrics' : 'ga:visitors',
'dimensions' : 'ga:pagePath,ga:pageTitle',
'start-date' : start_date,
'end-date' : end_date,
'sort' : '-ga:visitors',
'filters' : 'ga:pagePath=~%s' % pattern,
'max-results' : max_results,
}
data = self.get_data(query_params)
pages = []
for entry in data.entry:
page = Page.get_from_entry(entry)
pages.append(page)
return pages
class Page(object):
def __init__(self, title=None, path=None, visits=None, entry=None):
self.title = title
self.path = path
self.visits = visits
self.entry = entry
@classmethod
def get_from_entry(cls, entry):
title = entry.get_dimension('ga:pageTitle').value
path = entry.get_dimension('ga:pagePath').value
visits = entry.get_metric('ga:visitors').value
return Page(title=title, path=path,
visits=visits, entry=entry)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment