谷歌分析与Python
我刚开始学习Python,想给一个应用写个扩展,目的是导入GA(谷歌分析)信息并把它解析到MySQL里。关于这个话题的信息实在是太少了。谷歌文档里似乎只有JavaScript和Java的例子……
……我已经让用户可以通过SubAuth登录GA了。相关的代码在这里:
import gdata.service
import gdata.analytics
from django import http
from django import shortcuts
from django.shortcuts import render_to_response
def authorize(request):
next = 'http://localhost:8000/authconfirm'
scope = 'https://www.google.com/analytics/feeds'
secure = False # set secure=True to request secure AuthSub tokens
session = False
auth_sub_url = gdata.service.GenerateAuthSubRequestUrl(next, scope, secure=secure, session=session)
return http.HttpResponseRedirect(auth_sub_url)
接下来,我需要获取数据。我找到一个库:(注意,界面不太友好) http://gdata-python-client.googlecode.com/svn/trunk/pydocs/gdata.analytics.html。不过,我发现这个库有点难用。我觉得我应该用到gdata.analytics.AnalyticsDataEntry.getDataEntry(),但我不太确定需要传什么参数给它。
我希望能得到一些正确的指引。我感觉我在谷歌上找了很多例子,但都没有找到能用的。
谢谢!!
编辑:我已经进展了一些,但问题还是没解决。下面的方法返回了一些数据(我认为是)……我遇到的错误是:“'str'对象没有'_BecomeChildElement'这个属性”。我觉得我返回的是一个feed(数据流)?但是,我不知道怎么深入查看这个数据。有没有办法让我检查这个对象呢?
def auth_confirm(request):
gdata_service = gdata.service.GDataService('iSample_acctSample_v1.0')
feedUri='https://www.google.com/analytics/feeds/accounts/default?max-results=50'
# request feed
feed = gdata.analytics.AnalyticsDataFeed(feedUri)
print str(feed)
3 个回答
在这个应用里,你需要准备三个文件:client_secrets.json、analytics.dat 和 google_auth.py。
在应用里创建一个叫做 Query.py 的模块:
class Query(object):
def __init__(self, startdate, enddate, filter, metrics):
self.startdate = startdate.strftime('%Y-%m-%d')
self.enddate = enddate.strftime('%Y-%m-%d')
self.filter = "ga:medium=" + filter
self.metrics = metrics
下面是一个 models.py 的例子:#里面有以下这个功能
import google_auth
service = googleauth.initialize_service()
def total_visit(self):
object = AnalyticsData.objects.get(utm_source=self.utm_source)
trial = Query(object.date.startdate, object.date.enddate, object.utm_source, ga:sessions")
result = service.data().ga().get(ids = 'ga:<your-profile-id>', start_date = trial.startdate, end_date = trial.enddate, filters= trial.filter, metrics = trial.metrics).execute()
total_visit = result.get('rows')
<yr save command, ColumnName.object.create(data=total_visit) goes here>
我使用谷歌分析(GA)已经一年多了,从2009年4月开始,我用的是一个叫做python-googleanalytics的包,这个包是Clint Ecker等人提供的Python接口。到目前为止,它的表现相当不错。
你可以在这里找到这个包:http://github.com/clintecker/python-googleanalytics。
安装方法和其他软件一样,照常来就行。
使用这个包之前,首先为了避免每次访问API时都要手动输入登录信息,你可以把这些信息放在一个配置文件里,格式如下:
[Credentials]
google_account_email = youraccount@gmail.com
google_account_password = yourpassword
把这个文件命名为'.pythongoogleanalytics',然后放在你的主目录下。
接下来,在交互式命令行中输入:
from googleanalytics import Connection
import datetime
connection = Connection() # pass in id & pw as strings **if** not in config file
account = connection.get_account(<*your GA profile ID goes here*>)
start_date = datetime.date(2009, 12, 01)
end_data = datetime.date(2009, 12, 13)
# account object does the work, specify what data you want w/
# 'metrics' & 'dimensions'; see 'USAGE.md' file for examples
account.get_data(start_date=start_date, end_date=end_date, metrics=['visits'])
这个'get_account'方法会返回一个Python的列表(在上面的例子中,这个列表被绑定到变量'account'),里面包含了你的数据。
也许这篇文章能帮到你。看起来现在还没有专门针对分析的绑定,所以你需要使用通用的gdata。