最近接到比較奇怪的需求,必須要撈取臉書一些東西 ,今天這篇文章分享一下
如何抓到臉書的每一個的 facebook uid 但是不用用到 access token
其實,我大概研究一下,因為現在 Facebook Graph API 其實非常嚴格,目前要解決的做法
大概就是使用爬蟲,但是這裏面有分成他有設成 公開 或是 非公開 如果是公開你用無痕視窗看到會長這樣
如果是未公開,就會是長這樣,要你登入
但是透過原始碼是可以知道 user Id 的,但是就是得用程式去看,用瀏覽器的檢視原始碼不一定看得到的
就直接給程式碼吧,給後面有需要的人
var userIdAlias = "zuck";
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/{USER_ALIAS}";
string url = "https://www.facebook.com/"+userIdAlias;
HttpResponseMessage response = client.GetAsync(url).Result;
// 確保請求成功
response.EnsureSuccessStatusCode();
// 取得回應內容
var responseBody = response.Content.ReadAsStringAsync().Result;
//for private user profile
var pattern = @"""entity_id"":""(\d+)""}";
//for public user profile
var pattern2 = @"""userID"":""(\d+)""";
var match = Regex.Match(responseBody, pattern);
// 檢查是否找到匹配
if (match.Success)
{
// 取得捕獲組中的值
string userId = match.Groups[1].Value;
// 將找到的數字輸出
Console.WriteLine($"User Facebook UId (PRIVATE PROFILE): {userId}");
}
else
{
//找不到,有可能是 public profile 就用其他方法抓
match = Regex.Match(responseBody, pattern2);
if (match.Success) {
string userId = match.Groups[1].Value;
Console.WriteLine($"User Facebook UId (PUBLIC PROFILE): {userId}");
}
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Request Error: {ex.Message}");
}
}