>我正在尝试从 API 中提取广告系列费用/总支出我是 100% 的 API 新手,但我无法破解它
我想:1-获取每个广告系列的费用2-获取显示在GUI上的广告系列ID,而不仅仅是那种奇怪的代码,即8cdfn与1448530943
这是我到目前为止的 Python 代码
from twitter_ads.client import Client
from twitter_ads.cursor import Cursor
from twitter_ads.http import Request
from twitter_ads.error import Error
import time
from twitter_ads.campaign import LineItem
from twitter_ads.enum import METRIC_GROUP
from twitter_ads.enum import GRANULARITY
client = Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
account = client.accounts(ACCOUNT_ID)
cids = map(lambda x: x.id, account.campaigns())
resource = ‘/2/stats/accounts/{account_id}/’.format(account_id=account.id)
params = { ‘entity’:‘CAMPAIGN’,
‘entity_ids’:cids,
‘start_time’: ‘2017-12-10’,
‘end_time’:‘2017-12-16’,
‘granularity’:‘TOTAL’,
‘metric_groups’: ‘BILLING’,
‘placement’: ‘PUBLISHER_NETWORK’}
try, build and execute the request with error handling
try:
response = Request(client, ‘get’, resource, params=params).perform()
print(response.body[‘data’])
except Error as e:
# see twitter_ads.error for more details
print e.details
raise
这是对我有用的解决方案诀窍是传递多个展示位置在 API 中不起作用
from datetime import date,timedelta
import datetime
import logging
import sys
import os
import gzip
import shutil
import csv
import requests
import json
from twitter_ads.client import Client
from twitter_ads.cursor import Cursor
from twitter_ads.http import Request
from twitter_ads.error import Error
from twitter_ads.client import Client
from twitter_ads.campaign import LineItem
from twitter_ads.enum import METRIC_GROUP
from twitter_ads.enum import GRANULARITY
import twitter_ads
import time
client = Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
# load the advertiser account instance
account = client.accounts(ACCOUNT_ID)
cids = list(map(lambda x: x.id.encode('utf-8'), account.campaigns()))
campaigns = list(map(lambda x: [x.id.encode('utf-8'),x.name.encode('utf-8'), int(x.id,36)] , account.campaigns()))
resource = '/2/stats/accounts/{account_id}/'.format(account_id=account.id)
spend=[]
for c in campaigns:
for p in ['ALL_ON_TWITTER', 'PUBLISHER_NETWORK']:
params = { 'entity':'CAMPAIGN',
'entity_ids':c[0], #cids,
'start_time': target_date,
'end_time':target_date+timedelta(1),
'granularity':'DAY',
'metric_groups': ['BILLING','ENGAGEMENT'],
'placement': p
}
# try, build and execute the request with error handling
try:
req =Request(client, 'get', resource, params=params)
response = req.perform()
val = response.body['data']
val.append(p)
val.append(c[0])
val.append(c[1])
val.append(c[2])
spend.append(val)
except Error as e:
# see twitter_ads.error for more details
print e.details
raise
ddd= json.loads(json.dumps(spend))
with open(target_path+row['account_id']+'_campaign_spend.csv', "w") as output:
writer = csv.writer(output, lineterminator='n')
writer.writerow(['time_id','campaign_id_36', 'campaign_id','campaign_desc','placement','spend_micro', 'account_id'])
for val in ddd:
if (val[0]["id_data"][0]["metrics"]['billed_charge_local_micro'] and val[0]["id_data"][0]["metrics"]['billed_charge_local_micro'][0]):
writer.writerow([str(target_date).replace("/","-"),val[2],val[4],val[3],val[1], val[0]["id_data"][0]["metrics"]['billed_charge_local_micro'][0], ACCOUNT_ID])
我使用了你最初写的大部分内容来满足我自己的最新需求。 这就是我想出的:
from twitter_ads.client import Client
from twitter_ads.enum import ENTITY, GRANULARITY, METRIC_GROUP, PLACEMENT
from twitter_ads.http import Request
from twitter_ads.error import Error
from datetime import date, timedelta
CONSUMER_KEY = "CONSUMER_KEY"
CONSUMER_SECRET = "CONSUMER_SECRET"
ACCESS_TOKEN = "ACCESS_TOKEN"
ACCESS_TOKEN_SECRET = "ACCESS_TOKEN_SECRET"
ACCOUNT_ID = "ACCOUNT_ID"
client = Client(consumer_key=CONSUMER_KEY,
consumer_secret=CONSUMER_SECRET,
access_token=ACCESS_TOKEN,
access_token_secret=ACCESS_TOKEN_SECRET)
# For yesterday's total spend - for other date ranges you'll naturally need to
# update these two variables
time_offset = "T00:00:00-04:00"
yesterday = (date.today() - timedelta(1)).strftime("%Y-%m-%d") + time_offset
today = str(date.today()) + time_offset
# Could be done in a campaign loop as well ...
# account = client.accounts(id=ACCOUNT_ID)
# for camp in account.campaigns():
# print(str(camp.id) + ": " + camp.name)
resource = f"/7/stats/accounts/{ACCOUNT_ID}/"
params = {
"entity": ENTITY.CAMPAIGN,
"entity_ids": "CAMPAIGN ID HERE",
"start_time": yesterday,
"end_time": today,
"granularity": GRANULARITY.TOTAL,
"metric_groups": METRIC_GROUP.BILLING,
"placement": PLACEMENT.ALL_ON_TWITTER
}
try:
req = Request(client=client,
method="GET",
resource=resource,
params=params)
response = req.perform()
# Total spend in "micros"; for USD, $37.50 is represented as 37500000
spend_in_micros = response.body["data"][0]["id_data"][0]["metrics"]["billed_charge_local_micro"][0]
spend = round((spend_in_micros / 1000000), 2)
print(spend)
except Error as e:
print(e.details)
raise
免责声明:我是pywindsorai的贡献者。
假设您只需要点击(或支出(数据,您也可以使用 windsor.ai 来执行此操作,这使用起来更简单一些。你只需要将你的Twitter帐户连接到 windsor.ai,然后使用他们的Python SDK(pywindsorai(将数据加载到pandas中。
import pandas as pd
from pywindsorai.client import Client
from pywindsorai.enums import LAST_7D
from pywindsorai.enums import FIELD_SOURCE, FIELD_CAMPAIGN, FIELD_CLICKS
api_key = 'xxx' # Get this from your windsor.ai account
client = Client(api_key)
campaign_clicks = client.connectors(date_preset=LAST_7D, fields=[FIELD_SOURCE, FIELD_CAMPAIGN, FIELD_CLICKS])
df = pd.DataFrame(campaign_clicks['data'])
我试图得到同样的东西,但我做不到。我遵循所有提出的解决方案,但我收到了以下答案:' req =Request(Client, 'get', resource, params=params(
response =req.perform()
val = response.body['data']
val.append(p)
val.append(c[0])`