Perhaps if you want to use the Google Analytics API from Python, [Python Quick Start](https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/service-py?hl=ja# Did you see enable)? However, if you go this way, in step 3
Traceback (most recent call last):
File "test.py", line 6, in <module>
from oauth2client.client import SignedJwtAssertionCredentials
ImportError: cannot import name SignedJwtAssertionCredentials
It didn't work next to me. (As of March 20, 2016)
As conclusion
The solution was to use ServiceAccountCredentials
instead ofSignedJwtAssertionCredentials
.
This time, I applied this change and created sample that outputs the ranking of the number of pageviews.
python uses Python 2.7.6.
Go to step 2 of Python Quick Start
Please get.
Download the Github repository. Place the P12 key file you created earlier in the downloaded folder.
Prepare the json file
cp config.json.sample config.json
Edit the contents of config.json as follows.
{
"email": "<your google developer email adress> ex) [email protected] ",
"key": "<*.p12 path> ex) ./sample-5a5a55a5a5a5.p12",
"start_date": "Start date of ranking period ex) 2016-02-07", "end_date": "End date of ranking period ex) 2016-03-07", "home": "URL of page to analyze ex) http://qiita.com" }
Put the following two with pip
sudo pip install --upgrade google-api-python-client
pip install pyopenssl
I will do it
python googel_analystic_api_ranking.py
The following parts determine the content of the ranking.
def get_rankings_results(service, profile_id, config):
return service.data().ga().get(
ids='ga:' + profile_id,
start_date=config['start_date'],
end_date=config['end_date'],
sort='-ga:pageviews',
max_results='10',
dimensions='ga:pageTitle,ga:pagePath',
metrics='ga:pageviews').execute()
sort ='-ga: pageviews',
is sorted by ga: pageviews
and is acquired in descending order by the first-
.
The Analytics API gets the results in the form of a matrix.
At this time, specify the upper limit of the number of rows of the result acquired by the API with max_results
.
Also, the contents to be acquired are decided by dimensions
and metrics
.
This time, dimensions
specifies the page title and page path, and metrics
specifies the number of page views.
As an image, you can see metrics
for each dimensions
.
The result is output in the following part.
def print_rankings_results(results, home):
# Print data nicely for the user.
if results:
print(u'-----------Ranking Top 10-----------')
for col in results.get('rows'):
print(u'{0}\t{1}{2}\t{3}'.format(col[0], home, col[1], col[2]))
else:
print ('No results found')
The argument results
contains the response from the API obtained by the previous get_rankings_results
.
You can also access each row of results with'results.get ('rows')'.
The results are arranged in the order of dimensions
, metrics
, so you can get the pagePath of the first result by doing'results.get ('rows') [0] [1]'.
Recommended Posts