You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过API获取Instagram关注用户的动态(点赞、评论等)?

Hey there! Let's walk through how you can pull your followed Instagram users' activity—like their posts, likes, and comment lists—using the API, with examples in Node.js and Python since those are your top picks.

First, the Prerequisites

Before diving into code, you'll need to set up a few things on Instagram's developer side:

  • Create a Facebook Developer Account (since Instagram's API is tied to Facebook now)
  • Register a new app and link it to your Instagram account
  • Request the necessary permissions: user_followed_list (to get who you follow), user_media (to access posts), comments and likes (to pull those details)
  • Generate a valid access token with the above scopes

Make sure to review Instagram's API rate limits and platform policies—you don't want to get your app restricted!

Node.js Implementation

We'll use axios for HTTP requests here. First install the dependency:

npm install axios

Here's a sample script to fetch followed users, their recent posts, and associated likes/comments:

const axios = require('axios');

// Replace these with your actual credentials
const ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN';
const INSTAGRAM_USER_ID = 'YOUR_INSTAGRAM_USER_ID';

async function fetchFollowedUsers() {
  try {
    // Step 1: Get list of users you follow
    const followedResponse = await axios.get(`https://graph.instagram.com/${INSTAGRAM_USER_ID}/following`, {
      params: {
        fields: 'id,username',
        access_token: ACCESS_TOKEN
      }
    });

    const followedUsers = followedResponse.data.data;
    console.log('Followed users:', followedUsers);

    // Step 2: For each user, fetch their recent posts
    for (const user of followedUsers) {
      const mediaResponse = await axios.get(`https://graph.instagram.com/${user.id}/media`, {
        params: {
          fields: 'id,caption,media_type',
          access_token: ACCESS_TOKEN
        }
      });

      const userMedia = mediaResponse.data.data;
      if (userMedia.length === 0) continue;

      // Step 3: Fetch likes and comments for the first post (example)
      const firstPostId = userMedia[0].id;
      
      // Get likes
      const likesResponse = await axios.get(`https://graph.instagram.com/${firstPostId}/likes`, {
        params: {
          access_token: ACCESS_TOKEN
        }
      });
      console.log(`Likes for ${user.username}'s post ${firstPostId}:`, likesResponse.data.data);

      // Get comments
      const commentsResponse = await axios.get(`https://graph.instagram.com/${firstPostId}/comments`, {
        params: {
          access_token: ACCESS_TOKEN
        }
      });
      console.log(`Comments for ${user.username}'s post ${firstPostId}:`, commentsResponse.data.data);
    }
  } catch (error) {
    console.error('Error fetching data:', error.response?.data || error.message);
  }
}

fetchFollowedUsers();
Python Implementation

We'll use the requests library here. Install it first:

pip install requests

Here's a similar Python script:

import requests

# Replace these with your actual credentials
ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN'
INSTAGRAM_USER_ID = 'YOUR_INSTAGRAM_USER_ID'

def fetch_followed_users():
    try:
        # Step 1: Get list of followed users
        followed_url = f"https://graph.instagram.com/{INSTAGRAM_USER_ID}/following"
        followed_params = {
            'fields': 'id,username',
            'access_token': ACCESS_TOKEN
        }
        followed_response = requests.get(followed_url, params=followed_params)
        followed_response.raise_for_status()
        followed_users = followed_response.json()['data']
        print('Followed users:', followed_users)

        # Step 2: Fetch each user's recent posts
        for user in followed_users:
            media_url = f"https://graph.instagram.com/{user['id']}/media"
            media_params = {
                'fields': 'id,caption,media_type',
                'access_token': ACCESS_TOKEN
            }
            media_response = requests.get(media_url, params=media_params)
            media_response.raise_for_status()
            user_media = media_response.json()['data']
            if not user_media:
                continue

            # Step 3: Get likes and comments for the first post
            first_post_id = user_media[0]['id']
            
            # Fetch likes
            likes_url = f"https://graph.instagram.com/{first_post_id}/likes"
            likes_response = requests.get(likes_url, params={'access_token': ACCESS_TOKEN})
            likes_response.raise_for_status()
            print(f"Likes for {user['username']}'s post {first_post_id}:", likes_response.json()['data'])

            # Fetch comments
            comments_url = f"https://graph.instagram.com/{first_post_id}/comments"
            comments_response = requests.get(comments_url, params={'access_token': ACCESS_TOKEN})
            comments_response.raise_for_status()
            print(f"Comments for {user['username']}'s post {first_post_id}:", comments_response.json()['data'])

    except requests.exceptions.RequestException as e:
        print('Error fetching data:', e.response.json() if e.response else str(e))

if __name__ == "__main__":
    fetch_followed_users()
A Few Notes
  • The examples above only fetch the first post for each followed user—you can loop through all media items if needed.
  • If you need access to more granular data (like who liked a specific post), make sure your access token has the correct permissions.
  • Instagram's Graph API has rate limits, so add delays between requests if you're fetching data for many users to avoid being blocked.

内容的提问来源于stack exchange,提问作者Uğur Cem Öztürk

火山引擎 最新活动