加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用.NET / C#从Google AnalyticsAPI检索数据

发布时间:2020-12-15 22:01:49 所属栏目:百科 来源:网络整理
导读:我正在尝试使用本地控制台应用从谷歌分析中检索数据.我能够提取一些数据,而无需登录谷歌帐户,只使用API??. 问题是我没有得到正确的值,我不知道如何格式化代码以提取正确的值.我不想在特定时间范围内检索所有访客,在本例中为“2012-01-01” – “2014-02-20”
我正在尝试使用本地控制台应用从谷歌分析中检索数据.我能够提取一些数据,而无需登录谷歌帐户,只使用API??.

问题是我没有得到正确的值,我不知道如何格式化代码以提取正确的值.我不想在特定时间范围内检索所有访客,在本例中为“2012-01-01” – “2014-02-20”.查看Google Analytics信息中心时,实际访问者数量会增加10倍.在调试代码时,我得到了15000.我在控制台中显示d.TotalResults可能是错误的,变量“d”包含许多不同的属性.

这是我正在运行的代码:

public static void Main(string[] args)
{
    var serviceAccountEmail = "MY@developer.gserviceaccount.com";

    var certificate = new X509Certificate2(@"C:UsersUserDesktopkey.p12","notasecret",X509KeyStorageFlags.Exportable);

    var credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(serviceAccountEmail)
    {
        Scopes = new[] { AnalyticsService.Scope.Analytics }
    }.FromCertificate(certificate));

    // Create the service.
    //Twistandtango
    var gas = new AnalyticsService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,ApplicationName = "TestGoogleAnalytics",});

    var r = gas.Data.Ga.Get("ga:MYProfileID","2012-01-01","2014-02-20","ga:visitors");

    //Specify some addition query parameters
    r.Dimensions = "ga:pagePath";
    r.Sort = "-ga:visitors";
    r.MaxResults = 5;

    //Execute and fetch the results of our query
    Google.Apis.Analytics.v3.Data.GaData d = r.Execute();


    Console.WriteLine(d.TotalResults);
    Console.ReadLine();
}

我正在尝试使用此工具https://ga-dev-tools.appspot.com/explorer/查询我想要的结果.当我在我的代码中实现它时,它看起来像这样:

public static void Main(string[] args)
{
    var serviceAccountEmail = "MY@developer.gserviceaccount.com";

    var certificate = new X509Certificate2(@"C:UsersUserDesktopkey.p12",X509KeyStorageFlags.Exportable);

    var credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(serviceAccountEmail)
                {
                    Scopes = new[] { AnalyticsService.Scope.Analytics }
                }.FromCertificate(certificate));

                // Create the service.
                //Twistandtango
                var gas = new AnalyticsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,});

                var r = gas.Data.Ga.Get("ga:MYProfileID","ga:visits");

                //Specify some addition query parameters
                r.Dimensions = "ga:visitCount";
                r.Metrics = "ga:visits";
                r.Segment = "gaid::-1";
                //r.Sort = "-ga:visitors";
                r.MaxResults = 10000;

                //Execute and fetch the results of our query
                Google.Apis.Analytics.v3.Data.GaData d = r.Execute();


                Console.WriteLine(d.TotalResults);
                Console.ReadLine();
            }
        }

但是,在将指标(r.Metrics =“ga:visits”;)添加到项目后,我收到此错误:

Error 7 Property or indexer ‘Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest.Metrics’ cannot be assigned to — it is read only

此处还有分析v3中的类索引:

https://developers.google.com/resources/api-libraries/documentation/analytics/v3/csharp/latest/annotated.html

有谁知道这是如何工作的?如何从我指定的时间范围中检索访客总数?

谢谢

解决方法

您的问题是您在data.ga.get方法中提供指标,您不使用r.metrics指标添加更多它们一个单独的,用,.在这种情况下,ga:visits是您要求的指标.

var r = gas.Data.Ga.Get("ga:MYProfileID","ga:visits");

尺寸不是必填项,因此您可以删除r.Dimensions =“ga:visitCount”;看看它返回了什么.

请记住,只需做Google.Apis.Analytics.v3.Data.GaData d = r.Execute();如果有更多的结果设置为最大结果,则不会返回所有行.您需要检查下一个链接以确保没有更多行.

关于下一个链接更新以回答下面的问题.
您当前将max-results设置为10000,这是可以在块中返回的最大行数.如果有超过10000行,那么你将得到一个nextlink,你需要请求下一行行. TotalResult将为您提供应返回的总行数.下面我继续使用.execute请求更多数据,直到没有下一个链接.

List result = new List();
 do {
     try
       {
       GaData DataList = request.Execute();  // Make the request
       result.AddRange(DataList.Rows);       // store the Data to return later
       // hack to get next link stuff
      totalResults = (!DataList.TotalResults.HasValue) ? 0 : Int32.Parse(DataList.TotalResults.ToString());
       rowcnt = rowcnt + DataList.Rows.Count;
       NextLink = DataList.NextLink;                       
       request.StartIndex = rowcnt + 1 ;
       }
      catch (Exception e)
         {
          Console.WriteLine("An error occurred: " + e.Message);
          totalResults = 0;
         }
 } while (request.StartIndex <= totalResults);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读