廣告是移動應(yīng)用非常好的變現(xiàn)模式,作為開發(fā)者經(jīng)常會接很多家的廣告平臺,每個廣告平臺都有自己的報表系統(tǒng),就會有一個各個平臺數(shù)據(jù)匯總分析的需求,首先第一步就需要從各個廣告平臺獲取數(shù)據(jù),除了在web頁面提供基本的數(shù)據(jù)導(dǎo)出功能,基本上各個平臺都會提供 api 來方便數(shù)據(jù)拉取的自動化。
admob 是 google 的移動開發(fā)者廣告平臺,同樣也提供了完備的 api 來獲取報表數(shù)據(jù)
創(chuàng)建 API 憑證
報表 api 使用 oauth 2.0 授權(quán),需要先開通云平臺賬號,需要填一下賬單信息。開通賬號后,在平臺上創(chuàng)建一個 oauth 2.0 的憑證
google oauth 授權(quán)
創(chuàng)建完成后,下載JSON 秘鑰文件,保存為 client_secrets.json
使用 google api 的 python 庫
sudo pip3 install google-api-python-client
sudo pip3 install oauth2client
初始化服務(wù)
from apiclient import sample_tools
scope = ['https://www.googleapis.com/auth/adsense.readonly']
client_secrets_file = 'client_secrets.json'
service, _ = sample_tools.init(
'', 'adsense', 'v1.4', __doc__,
client_secrets_file,
parents=[], scope=scope
)
調(diào)用服務(wù) api
results = service.accounts().reports().generate(
accountId='pub-131xxxxxxxxxxxxx',
startDate=start.strftime('%Y-%m-%d'),
endDate=end.strftime('%Y-%m-%d'),
metric=metric,
dimension=dimension,
useTimezoneReporting=True,
).execute()
accountId: 在 admob 平臺的首頁上https://apps.admob.com/v2/home點(diǎn)擊自己的頭像,發(fā)布商ID就是accountId
metric: 指標(biāo)項,點(diǎn)擊、展示、收入等
dimension: 維度,日期、app、廣告位、國家等
startDate: 開始日期,yyyy-mm-dd 格式
endDate: 結(jié)束時間,yyyy-mm-dd 格式
useTimezoneReporting: 使用賬戶所在的時區(qū)
參考代碼
代碼依賴了一個client_secrets.json的授權(quán)文件
import json
import datetime
import argparse
from apiclient import sample_tools
def collect(start=None, end=None):
if not start:
start = datetime.datetime.now() - datetime.timedelta(days=1)
if not end:
end = start
scope = ['https://www.googleapis.com/auth/adsense.readonly']
client_secrets_file = 'client_secrets.json'
service, _ = sample_tools.init(
'', 'adsense', 'v1.4', __doc__,
client_secrets_file,
parents=[], scope=scope
)
dimension = [
"DATE", "APP_NAME", "APP_PLATFORM", "AD_UNIT_NAME", "AD_UNIT_ID", "COUNTRY_CODE"
]
metric = [
"AD_REQUESTS", "CLICKS", "INDIVIDUAL_AD_IMPRESSIONS", "EARNINGS", "REACHED_AD_REQUESTS_SHOW_RATE"
]
results = service.accounts().reports().generate(
accountId='pub-131xxxxxxxxxxxxx',
startDate=start.strftime('%Y-%m-%d'),
endDate=end.strftime('%Y-%m-%d'),
metric=metric,
dimension=dimension,
useTimezoneReporting=True,
).execute()
headers = [i.lower() for i in dimension + metric]
datas = []
for row in results.get('rows'):
data = {}
for i in range(len(row)):
data[headers[i]] = row[i]
datas.append(data)
return datas
def transform(datas):
for data in datas:
# 數(shù)據(jù)轉(zhuǎn)化
pass
return datas
def serialize(datas):
for data in datas:
print(json.dumps(data))
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description="""Example:
python3 admob.py -s 20181025 -e 20181028
"""
)
parser.add_argument(
'-s', '--start',
type=lambda d: datetime.datetime.strptime(d, '%Y%m%d'),
help='start time',
default=None
)
parser.add_argument(
'-e', '--end',
type=lambda d: datetime.datetime.strptime(d, '%Y%m%d'),
help='end time',
default=None
)
args = parser.parse_args()
serialize(transform(collect(args.start, args.end)))
if __name__ == '__main__':
main()
參考鏈接
·google 廣告平臺報表 api: https://developers.google.com/adsense/management/v1.4/reference/accounts/reports/generate
·google 廣告平臺指標(biāo)和維度:
https://developers.google.com/adsense/management/metrics-dimensions
·google oauth 授權(quán): https://developers.google.com/adwords/api/docs/guides/authentication
·How to use Google Adsense API to download Adsense data: https://009co.com/?p=389
·google admob 平臺: https://apps.admob.com/v2/home
·google 云平臺: https://console.cloud.google.com/home/dashboard
·adsense 平臺憑據(jù): https://console.cloud.google.com/apis/credentials