-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathProgram.cs
More file actions
90 lines (77 loc) · 2.46 KB
/
Copy pathProgram.cs
File metadata and controls
90 lines (77 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Competitor Tracker: monitor your brand vs competitors across search engines.
// Use case: Marketing teams tracking SERP visibility for key terms.
// Runs searches across Google and Bing, reports who ranks where.
using SerpApi;
using System.Text.Json;
var apiKey = args.Length > 0 ? args[0] : Environment.GetEnvironmentVariable("SERPAPI_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Usage: dotnet run -- <API_KEY>");
Console.WriteLine(" or: SERPAPI_KEY=... dotnet run");
return;
}
using var client = new SerpApiClient(apiKey);
var keyword = "project management software";
var trackedDomains = new[] { "asana.com", "monday.com", "clickup.com", "notion.so" };
Console.WriteLine($"Tracking: \"{keyword}\"");
Console.WriteLine($"Domains: {string.Join(", ", trackedDomains)}\n");
// Search Google and Bing in parallel
var google = client.SearchAsync(new Dictionary<string, string>
{
["engine"] = "google_light",
["q"] = keyword,
["num"] = "20"
});
var bing = client.SearchAsync(new Dictionary<string, string>
{
["engine"] = "bing",
["q"] = keyword,
["count"] = "20"
});
try
{
await Task.WhenAll(google, bing);
var engines = new[] { ("Google", await google), ("Bing", await bing) };
foreach (var (engineName, response) in engines)
{
Console.WriteLine($"=== {engineName} Rankings ===");
var organic = response.OrganicResults;
if (organic is not { } results)
{
Console.WriteLine(" No results\n");
continue;
}
foreach (var domain in trackedDomains)
{
var position = -1;
var idx = 0;
foreach (var r in results.EnumerateArray())
{
idx++;
var link = r.TryGetProperty("link", out var l) ? l.GetString() ?? "" : "";
if (link.Contains(domain, StringComparison.OrdinalIgnoreCase))
{
position = idx;
break;
}
}
var status = position > 0 ? $"#{position}" : "Not in top 20";
Console.WriteLine($" {domain,-20} {status}");
}
Console.WriteLine();
}
}
catch (SerpApiException ex)
{
Console.WriteLine($"Search error: {ex.Message}");
}
finally
{
DisposeCompleted(google);
DisposeCompleted(bing);
}
static void DisposeCompleted(Task<SerpApiResponse> task)
{
if (task.Status == TaskStatus.RanToCompletion)
task.Result.Dispose();
}