[C#] 不使用 access_token為前提取得臉書粉絲專頁的按讚數

2023-12-30

最近都接到比較奇怪的需求,對方要知道,粉絲團的按讚數,因為要 access_token

要取得該粉絲團的 access_token 就比較麻煩了,所以唯一能解決的方法就是爬蟲了



其實 facebook 大量使用 JS 從後端拿資料,其實不太有突破口,目前只有找到這一個

能用多久也不知道 我們用 https://facebook.com/Microsoft 做舉例

該臉書粉絲專業的 uid 是 20528438720 

所以我們要用的網址就是 https://www.facebook.com/plugins/fan.php?connections=100&id=20528438720

這時候就是透過 HttpClient 寫爬蟲惹,這裡面要注意,記得模擬瀏覽器,還有語系調成英文避免 你的 正規表述式失效


using (HttpClient client = new HttpClient()) { // 設定 User-Agent 為 Chrome client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"); // 設定 Accept-Language 為英文 client.DefaultRequestHeaders.Add("Accept-Language", "en-US"); try { // 要訪問的URL string url = "https://www.facebook.com/plugins/fan.php?connections=100&id=20528438720"; HttpResponseMessage response = client.GetAsync(url).Result; // 確保請求成功 response.EnsureSuccessStatusCode(); // 取得回應內容 var responseBody = response.Content.ReadAsStringAsync().Result; // 輸出回應內容 //">47,186 followers</div> var pattern = @">([\d,]+)\sfollowers<\/div>"; Match match = Regex.Match(responseBody, pattern); // 檢查是否找到匹配 if (match.Success) { // 取得捕獲組中的值 string followersCount = match.Groups[1].Value; // 將找到的數字輸出 Console.WriteLine($"Followers Count: {followersCount}"); } else { Console.WriteLine("No Match."); } } catch (HttpRequestException ex) { Console.WriteLine($"Request Error: {ex.Message}"); } }


result:
Followers Count: 13,153,328

就筆記一下,因為找方法找很久,給跟我一樣可憐的工程師


當麻許的碎念筆記 2014 | Donma Hsu Design.