使用Python按天从Yandex.Direct API获取所有客户端的统计信息

在我的工作中,我经常按天使用简短的统计信息来跟踪流量偏差。

他在文章“在DataFrame(Python)中使用API​​获取Yandex.Direct直接广告活动”中写了有关编写请求的更多信息。

在本文中,我将更多地讨论如何构造数据和查询以使其能够正常使用。

我们应该将服务器请求注册为功能。

我个人制作了2个文件:一个带有请求的函数和一个包含将被传输到该函数的数据的文件。

在第一个文件中,我们编写一个函数


我为所有项目都请求了相同的字段,因此我只需要传递日期,登录名和令牌。

将数据传递给我的函数看起来像这样:

def rep(token,login,date_from,date_to): 

我们正在向Yandex.Direct API服务器发送请求


该查询请求以下参数的数据:

  • 日期
  • 印象数
  • 点击次数
  • 点击率
  • 费用
  • Avgcpc
  • 平均印象位置
  • AvgClickPosition
  • 平均流量
  • 跳出率
  • 平均浏览量

最终请求文件


代号
 import requests from requests.exceptions import ConnectionError from time import sleep import json #        UTF-8   Python 3,    Python 2 import sys def rep(token,login,date_from,date_to): if sys.version_info < (3,): def u(x): try: return x.encode("utf8") except UnicodeDecodeError: return x else: def u(x): if type(x) == type(b''): return x.decode('utf8') else: return x # ---   --- #   Reports   JSON- () ReportsURL = 'https://api.direct.yandex.com/json/v5/reports' # OAuth- ,       token = token #     #  ,        clientLogin = login # ---   --- #  HTTP-  headers = { # OAuth-.   Bearer  "Authorization": "Bearer " + token, #     "Client-Login": clientLogin, #    "Accept-Language": "ru", #    "processingMode": "auto" #      # "returnMoneyInMicros": "false", #            # "skipReportHeader": "true", #         # "skipColumnHeader": "true", #          # "skipReportSummary": "true" } #    body = { "params": { "SelectionCriteria": { "DateFrom": date_from, "DateTo": date_to }, "FieldNames": [ "Date", "Impressions", "Clicks", "Ctr", "Cost", "AvgCpc", "AvgImpressionPosition", "AvgClickPosition", "AvgTrafficVolume", "BounceRate", "AvgPageviews", ], "ReportName": u("Report4"), "ReportType": "ACCOUNT_PERFORMANCE_REPORT", "DateRangeType": "CUSTOM_DATE", "Format": "TSV", "IncludeVAT": "NO", "IncludeDiscount": "NO" } } #     JSON body = json.dumps(body, indent=4) # ---      --- #   HTTP- 200,     #   HTTP- 201  202,    while True: try: req = requests.post(ReportsURL, body, headers=headers) req.encoding = 'utf-8' #      UTF-8 if req.status_code == 400: print("         ") print("RequestId: {}".format(req.headers.get("RequestId", False))) print("JSON- : {}".format(u(body))) print("JSON-  : \n{}".format(u(req.json()))) break elif req.status_code == 200: format(u(req.text)) break elif req.status_code == 201: print("       ") retryIn = int(req.headers.get("retryIn", 60)) print("    {} ".format(retryIn)) print("RequestId: {}".format(req.headers.get("RequestId", False))) sleep(retryIn) elif req.status_code == 202: print("    ") retryIn = int(req.headers.get("retryIn", 60)) print("    {} ".format(retryIn)) print("RequestId: {}".format(req.headers.get("RequestId", False))) sleep(retryIn) elif req.status_code == 500: print("    . ,    ") print("RequestId: {}".format(req.headers.get("RequestId", False))) print("JSON-  : \n{}".format(u(req.json()))) break elif req.status_code == 502: print("     .") print( ",     -      .") print("JSON- : {}".format(body)) print("RequestId: {}".format(req.headers.get("RequestId", False))) print("JSON-  : \n{}".format(u(req.json()))) break else: print("  ") print("RequestId: {}".format(req.headers.get("RequestId", False))) print("JSON- : {}".format(body)) print("JSON-  : \n{}".format(u(req.json()))) break #  ,       API  except ConnectionError: #         print("     API") #     break #   -   except: #         print("  ") #     break json_string = json.dumps(body) return req.text 


2档


我们分别取出日期,登录名和令牌作为变量。


像这样:

 # mytoken='blablablablaBLABLAsdfgsrgkdfgnf' # project = 'elama-99999999' # DateFrom="2019-04-08" DateTo="2019-04-16" 

这样做是为了轻松更改所有客户的信息以及报告日期。

请求项目统计信息的代码


 print( '\n=== ===') data=rep(mytoken,project,DateFrom,DateTo) file=open("cashe.csv","w") file.write(data) file.close() f=DataFrame.from_csv("cashe.csv",header=1,sep=' ',index_col=0,parse_dates=True) f['Cost']=f['Cost']*1.2 f['Cost']=f['Cost']/1000000 f['AvgCpc']=f['AvgCpc']*1.2 f['AvgCpc']=f['AvgCpc']/1000000 print(f) 

更多详细信息:

  1. 项目的名称(“ =“,我们用于更好的选择,以免迷失在信息中)
  2. 数据-将上面已指示的变量写入此行。 (此行将执行第一个文件)
  3. 我们将服务器响应写入文件
  4. 将文件作为DataFrame打开
  5. 添加到增值税的货币价值中。
  6. 我们将货币值转换为普通卢布(作为标准,API不使用卢布,而是使用卢布* 1,000,000。
  7. 输出我们的DataFrame



第二个文件如下:


代号
 # import pandas as pd import numpy as np from pandas import Series,DataFrame from     import rep #   pd.set_option('display.max_columns',None) pd.set_option('display.expand_frame_repr',False) pd.set_option('max_colwidth',-1) # mytoken='blablablablaBLABLAsdfgsrgkdfgnf' # project = 'elama-99999999' # DateFrom="2019-04-08" DateTo="2019-04-16" print( '\n=== ===') data=rep(mytoken,project,DateFrom,DateTo) file=open("cashe.csv","w") file.write(data) file.close() f=DataFrame.from_csv("cashe.csv",header=1,sep=' ',index_col=0,parse_dates=True) f['Cost']=f['Cost']*1.2 f['Cost']=f['Cost']/1000000 f['AvgCpc']=f['AvgCpc']*1.2 f['AvgCpc']=f['AvgCpc']/1000000 print(f) 


我们将所有项目写在第二个文件中,然后显示所有项目的统计信息。

之后,我们只需要在DateFrom和DateTo字段中更改时间长度即可。

Source: https://habr.com/ru/post/zh-CN449392/


All Articles