[C#] 不用 Access Token 如何獲取粉絲專頁的 UID
2024-02-29
記錄一下,最近有需求就是不要等入下取得臉書的公開資訊,所以目前解決方案就是
透過爬蟲,今天的範例,就是不登入狀況下,沒有 Access Token 下取得 LadyGaGa 臉書粉絲專業的 Fanspage ID
主要也是透過 embed fanpage 的網址
https://www.facebook.com/plugins/fan.php?connections=99&id=ladygaga
接下來就是透過 Regex Parse 取得的原始碼的部分
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
var fanspageCode = "ladygaga"; | |
try | |
{ | |
// 要訪問的URL | |
string url = "https://www.facebook.com/plugins/fan.php?connections=99&id="+ fanspageCode; | |
HttpResponseMessage response = client.GetAsync(url).Result; | |
// 確保請求成功 | |
response.EnsureSuccessStatusCode(); | |
// 取得回應內容 | |
var responseBody = response.Content.ReadAsStringAsync().Result; | |
//regex for get fanspage id | |
var pattern = @"href=""https://www\.facebook\.com/(\d+)\?ref=embed_page"""; | |
Match match = Regex.Match(responseBody, pattern); | |
// 檢查是否找到匹配 | |
if (match.Success) | |
{ | |
// 取得捕獲組中的值 | |
string followersCount = match.Groups[1].Value; | |
// 將找到的 id 輸出 | |
Console.WriteLine($"Fanspage UID: {followersCount}"); | |
} | |
else | |
{ | |
Console.WriteLine("No Match."); | |
} | |
} | |
catch (HttpRequestException ex) | |
{ | |
Console.WriteLine($"Request Error: {ex.Message}"); | |
} | |
} | |
就把這放在這希望幫到有需要的人