临时写的google analytics数据导出csv

导出内部搜索的关键字及访问数

[ccn lang="python" tab_size="4" theme="blackboard" width="900" ]
#!/app01/duser_home/wchga/dev/env/py/ga/bin/python
# -*- coding: utf-8 -*-

__author__ = 'ohergal@gmail.com (Fletcher)'

import gdata.analytics.client
import time, datetime
from pysqlite2 import dbapi2 as sqlite
import csv, codecs, cStringIO

class GADataFeed(object):
"""
GA数据导出到指定的数据源中,并获取需要的数据
"""
def __init__(self,tableId,account,passwd):
self.tableId = tableId
# 获取ga客户端并登录
self.ga_client = gdata.analytics.client.AnalyticsClient()
self.ga_client.client_login(account,passwd,'xdf')

def initQuery(self,query_dict):
"""
初始化查询的内容
"""
self.data_query = gdata.analytics.client.DataFeedQuery(query_dict)

def getFeedData(self,query_dict):
"""
获取数据源
"""
self.initQuery(query_dict)
self.gdata_feed = self.ga_client.GetDataFeed(self.data_query)
return self.gdata_feed

def getEntry(self,query_dict):
"""
获取数据实体
"""
self.getFeedData(query_dict)
return self.gdata_feed.entry
def getEncodeValues(self , dmetrics , code_name='utf-8'):
"""
把数据编码
"""
coded_list = [ m.value.encode(code_name) for m in dmetrics]
return coded_list

if __name__ == '__main__' :
account_email='xxxxx@xxxx.xxx'
account_passwd='xxxxxxxx'
table_id='ga:xxxxxxxx'
data_query_dict = {
'ids': table_id,
'start-date': '2010-06-01',
'end-date': '2010-11-22',
'dimensions': 'ga:searchKeyword',
'metrics': 'ga:visits',
'sort': '-ga:visits',
'filters': '',
'max-results': '10000'}
data_feed = GADataFeed(table_id,account_email,account_passwd)
data_entry = data_feed.getEntry(data_query_dict)
date_str = time.strftime("%y-%m-%d",time.localtime())
export_filename ="export" + date_str + ".csv"
export_writer = csv.writer(open(export_filename, "wb"))

for entry in data_entry:
dim1 = entry.dimension
met1 = entry.metric
data_dict = [dim1[0].value.encode("utf-8"),met1[0].value.encode("utf-8")]
try:
export_writer.writerow([s.decode('utf-8').encode('gbk') for s in data_dict])
except:
print dim1[0].value.encode("utf-8")
"""
for dim in entry.dimension:
print ('Dimension Name = %s \t Dimension Value = %s'
% (dim.name, dim.value))
for met in entry.metric:
print ('Metric Name = %s \t Metric Value = %s'
% (met.name, met.value))
print '---'
"""

[/ccn]
环境等下次有时间的时候 写上去
用try是为了防止非法字符的中断

评论

  1. gulin 回复

    看不懂啊,能不能说细点?我就是想把后台的关键字哪个表导出来,最好是excel表格, :neutral:

  2. admin 回复

    我这个就是导出关键词的

  3. admin 回复

    如果还是不明白邮件我

  4. IT 回复

    运行这个程序就可以导出关键词么? :!: :?:

留下评论

您的email地址不会被公开.

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据