Instagram API - How can I retrieve the list of people a user is following on Instagram

后端 未结 7 1648
你的背包
你的背包 2020-12-01 01:07

I would like to know how I can retrieve the list of people a user is following on Instagram. This is given that this particular user is someone that I follow. So I have acce

相关标签:
7条回答
  • 2020-12-01 01:50

    I made my own way based on Caitlin Morris's answer for fetching all folowers and followings on Instagram. Just copy this code, paste in browser console and wait for a few seconds.

    You need to use browser console from instagram.com tab to make it works.

    let username = 'USERNAME'
    let followers = [], followings = []
    try {
      let res = await fetch(`https://www.instagram.com/${username}/?__a=1`)
    
      res = await res.json()
      let userId = res.graphql.user.id
    
      let after = null, has_next = true
      while (has_next) {
        await fetch(`https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=` + encodeURIComponent(JSON.stringify({
          id: userId,
          include_reel: true,
          fetch_mutual: true,
          first: 50,
          after: after
        }))).then(res => res.json()).then(res => {
          has_next = res.data.user.edge_followed_by.page_info.has_next_page
          after = res.data.user.edge_followed_by.page_info.end_cursor
          followers = followers.concat(res.data.user.edge_followed_by.edges.map(({node}) => {
            return {
              username: node.username,
              full_name: node.full_name
            }
          }))
        })
      }
      console.log('Followers', followers)
    
      has_next = true
      after = null
      while (has_next) {
        await fetch(`https://www.instagram.com/graphql/query/?query_hash=d04b0a864b4b54837c0d870b0e77e076&variables=` + encodeURIComponent(JSON.stringify({
          id: userId,
          include_reel: true,
          fetch_mutual: true,
          first: 50,
          after: after
        }))).then(res => res.json()).then(res => {
          has_next = res.data.user.edge_follow.page_info.has_next_page
          after = res.data.user.edge_follow.page_info.end_cursor
          followings = followings.concat(res.data.user.edge_follow.edges.map(({node}) => {
            return {
              username: node.username,
              full_name: node.full_name
            }
          }))
        })
      }
      console.log('Followings', followings)
    } catch (err) {
      console.log('Invalid username')
    }
    
    0 讨论(0)
  • 2020-12-01 01:57

    Here's a way to get the list of people a user is following with just a browser and some copy-paste (A pure javascript solution based on Deep Seeker's answer):

    1. Get the user's id (In a browser, navigate to https://www.instagram.com/user_name/?__a=1 and look for response -> graphql -> user -> id [from Deep Seeker's answer])

    2. Open another browser window

    3. Open the browser console and paste this in it

      options = {
          userId: your_user_id,
          list: 1 //1 for following, 2 for followers
      }

    4. change to your user id and hit enter

    5. paste this in the console and hit enter

      `https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=` + encodeURIComponent(JSON.stringify({
              "id": options.userId,
              "include_reel": true,
              "fetch_mutual": true,
              "first": 50
          }))

    6. Navigate to the outputted link

    (This sets up the headers for the http request. If you try to run the script on a page where this isn't open, it won't work.)

    1. In the console for the page you just opened, paste this and hit enter
      let config = {
        followers: {
          hash: 'c76146de99bb02f6415203be841dd25a',
          path: 'edge_followed_by'
        },
        following: {
          hash: 'd04b0a864b4b54837c0d870b0e77e076',
          path: 'edge_follow'
        }
      };
      
      var allUsers = [];
      
      function getUsernames(data) {
          var userBatch = data.map(element => element.node.username);
          allUsers.push(...userBatch);
      }
      
      async function makeNextRequest(nextCurser, listConfig) {
          var params = {
              "id": options.userId,
              "include_reel": true,
              "fetch_mutual": true,
              "first": 50
          };
          if (nextCurser) {
              params.after = nextCurser;
          }
          var requestUrl = `https://www.instagram.com/graphql/query/?query_hash=` + listConfig.hash + `&variables=` + encodeURIComponent(JSON.stringify(params));
      
          var xhr = new XMLHttpRequest();
          xhr.onload = function(e) {
              var res = JSON.parse(xhr.response);
      
              var userData = res.data.user[listConfig.path].edges;
              getUsernames(userData);
      
              var curser = "";
              try {
                  curser = res.data.user[listConfig.path].page_info.end_cursor;
              } catch {
      
              }
              var users = [];
              if (curser) {
                  makeNextRequest(curser, listConfig);
              } else {
                  var printString =""
                  allUsers.forEach(item => printString = printString + item + "\n");
                  console.log(printString);
              }
          }
      
          xhr.open("GET", requestUrl);
          xhr.send();
      }
      
      if (options.list === 1) {
      
          console.log('following');
          makeNextRequest("", config.following);
      } else if (options.list === 2) {
      
          console.log('followers');
          makeNextRequest("", config.followers);
      }

    After a few seconds it should output the list of users your user is following.

    0 讨论(0)
  • 2020-12-01 01:58

    You can use Phantombuster. Instagram has set some rate limit, so you will have to use either multiple accounts or wait for 15 minutes for the next run.

    0 讨论(0)
  • 2020-12-01 02:02

    Shiva's answer doesn't apply anymore. The API call "/users/{user-id}/follows" is not supported by Instagram for some time (it was disabled in 2016).

    For a while you were able to get only your own followers/followings with "/users/self/follows" endpoint, but Instagram disabled that feature in April 2018 (with the Cambridge Analytica issue). You can read about it here.

    As far as I know (at this moment) there isn't a service available (official or unofficial) where you can get the followers/followings of a user (even your own).

    0 讨论(0)
  • 2020-12-01 02:05

    I've been working on some Instagram extension for chrome last few days and I got this to workout:

    First, you need to know that this can work if the user profile is public or you are logged in and you are following that user.

    I am not sure why does it work like this, but probably some cookies are set when you log in that are checked on the backend while fetching private profiles.

    Now I will share with you an ajax example but you can find other ones that suit you better if you are not using jquery.

    Also, you can notice that we have two query_hash values for followers and followings and for other queries different ones.

    let config = {
      followers: {
        hash: 'c76146de99bb02f6415203be841dd25a',
        path: 'edge_followed_by'
      },
      followings: {
        hash: 'd04b0a864b4b54837c0d870b0e77e076',
        path: 'edge_follow'
      }
    };
    

    The user ID you can get from https://www.instagram.com/user_name/?__a=1 as response.graphql.user.id

    After is just response from first part of users that u are getting since the limit is 50 users per request:

    let after = response.data.user[list].page_info.end_cursor
    
    let data = {followers: [], followings: []};
    
    function getFollows (user, list = 'followers', after = null) {
      $.get(`https://www.instagram.com/graphql/query/?query_hash=${config[list].hash}&variables=${encodeURIComponent(JSON.stringify({
        "id": user.id,
        "include_reel": true,
        "fetch_mutual": true,
        "first": 50,
        "after": after
      }))}`, function (response) {
        data[list].push(...response.data.user[config[list].path].edges);
        if (response.data.user[config[list].path].page_info.has_next_page) {
          setTimeout(function () {
            getFollows(user, list, response.data.user[config[list].path].page_info.end_cursor);
          }, 1000);
        } else if (list === 'followers') {
          getFollows(user, 'followings');
        } else {
          alert('DONE!');
          console.log(followers);
          console.log(followings);
        }
      });
    }
    

    You could probably use this off instagram website but I did not try, you would probably need some headers to match those from instagram page.

    And if you need for those headers some additional data you could maybe find that within window._sharedData JSON that comes from backend with csrf token etc.

    You can catch this by using:

    let $script = JSON.parse(document.body.innerHTML.match(/<script type="text\/javascript">window\._sharedData = (.*)<\/script>/)[1].slice(0, -1));
    

    Thats all from me!

    Hope it helps you out!

    0 讨论(0)
  • 2020-12-01 02:09

    You can use the following Instagram API Endpoint to get a list of people a user is following.

    https://api.instagram.com/v1/users/{user-id}/follows?access_token=ACCESS-TOKEN

    Here's the complete documentation for that endpoint. GET /users/user-id/follows

    And here's a sample response from executing that endpoint.

    Since this endpoint required a user-id (and not user-name), depending on how you've written your API client, you might have to make a call to the /users/search endpoint with a username, and then get the user-id from the response and pass it on to the above /users/user-id/follows endpoint to get the list of followers.

    IANAL, but considering it's documented in their API, and looking at the terms of use, I don't see how this wouldn't be legal to do.

    0 讨论(0)
提交回复
热议问题