我对此非常陌生,本周才开始关注python。
我目前正在尝试从Google Analytics中提取数据,需要提取多天的数据。然而,我在尝试将代码循环多天时遇到问题:
CODE:
for date in daterange( start, end ):
# EXTRACT OVERALL VISITS AND UNIQUE VISITS;
def get_results(service, profile_id):
return service.data().ga().get(
ids='ga:' + profile_id,
start_date=str(date),
end_date=str(date),
metrics='ga:visits,ga:newVisits,ga:visitors').execute()
但是这似乎没有循环,而是给我定义了最后一个日期的数据。
答案 0 :(得分:3)
你的for循环重复定义一个函数,但从不调用它。
试试这个:
def get_results(service, profile_id, date):
return service.data().ga().get(
ids='ga:' + profile_id,
start_date=str(date),
end_date=str(date),
metrics='ga:visits,ga:newVisits,ga:visitors').execute()
for date in daterange(start_date, end_date):
get_results(service, profile_id, date)
答案 1 :(得分:0)
for date in daterange( start, end ):
# EXTRACT OVERALL VISITS AND UNIQUE VISITS;
def get_results(service, profile_id):
return service.data().ga().get(
ids='ga:' + profile_id,
start_date=str(date),
end_date=str(date),
metrics='ga:visits,ga:newVisits,ga:visitors').execute()
# EXTRACT UNIQUE PAGE VIEWS FOR IMPORTANT STAGES;
def print_results(results):
if results:
# Print data nicely for the user.
print (results)
#print 'First Profile: %s' % results.get('profileInfo').get('profileName')
#print 'Total Visits: %s' % results.get('rows')[0][0]
#print 'Total New Visits: %s' % results.get('rows')[0][1]
#print 'Total Unique Visitors: %s' % results.get('rows')[0][2]
#print 'Unique Visitors Starting the Survey: %s' % results2.get('rows')[0][0]
#print 'Unique Visitors Completing the Survey: %s' % results3.get('rows')[0][0]
#print 'Unique Visitors Registering: %s' % results4.get('rows')[0][0]
#print f
# OUTPUT TO FILE.
# f.write (str(date) + ',' + results.get('rows')[0][0] + ',' + results.get('rows')[0][2] + ',' + results2.get('rows')[0][0] + ',' + results3.get('rows')[0][0] + ',' + results4.get('rows')[0][0] + '\n')
#f.close()
else:
print 'No results found'