我試圖從本地控制檯應用程序檢索谷歌分析數據。我能夠提取一些數據,而無需登錄到Google帳戶,只使用API。使用.NET/C從Google AnalyticsAPI檢索數據#
問題是我沒有得到正確的值,我不知道如何格式化代碼以提取正確的值。我不想在特定的時間範圍內檢索所有訪問者,在這種情況下「2012-01-01」 - 「2014-02-20」。在Google Analytics(分析)信息中心中查看時,真正的訪問者數量是10倍。調試代碼時,我得到了15000的數字。我在控制檯顯示d.TotalResults可能是錯誤的,變量「d」包含許多不同的屬性。
這是我運行代碼:
public static void Main(string[] args)
{
var serviceAccountEmail = "[email protected]";
var certificate = new X509Certificate2(@"C:\Users\User\Desktop\key.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 = "[email protected]";
var certificate = new X509Certificate2(@"C:\Users\User\Desktop\key.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: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:
沒有人有是如何工作的知識呢?我如何檢索我指定的時間範圍內的遊客總量?
THX
你也選擇了PagePath,你將不得不把它們總和,以獲得全部總數。你確定你不是在尋找訪問者還是訪客? – DaImTo
嗯,我只是在我指定的日期之間尋找所有訪問。所有訪問總數,新,舊等。我怎麼能總結他們呢?猜猜我還沒有弄清楚這是如何工作,嘗試了不同的維度和指標,但我認爲我沒有正確地格式化代碼,因爲我沒有得到我期望的結果。我認爲你可以結合過濾器或尺寸,但我不知道 – koffe14