Instagram API - 如何检索用户在Instagram上关注的人员列表

act*_*ner 30 instagram instagram-api

我想知道如何检索用户在Instagram上关注的人员列表.这是因为这个特定用户是我关注的人.所以我可以在Instagram应用程序上访问他/她的照片和他的粉丝.

我如何使用Instagram API执行此操作?这合法吗?

Jea*_*sta 87

/sf/answers/4413957621/的进一步开发版本

  1. 在浏览器上打开 Instagram;
  2. 登录 Instagram;
  3. 打开浏览器的控制台(CTRL++ SHIFTJ
  4. 粘贴下面的代码;
  5. 更新第一行的用户名;
  6. 运行它(点击Enter
const username = "USER_NAME_HERE";

/**
 * Initialized like this so we can still run it from browsers, but also use typescript on a code editor for intellisense.
 */
let followers = [{ username: "", full_name: "" }];
let followings = [{ username: "", full_name: "" }];
let dontFollowMeBack = [{ username: "", full_name: "" }];
let iDontFollowBack = [{ username: "", full_name: "" }];

followers = [];
followings = [];
dontFollowMeBack = [];
iDontFollowBack = [];

(async () => {
  try {
    console.log(`Process started! Give it a couple of seconds`);

    const userQueryRes = await fetch(
      `https://www.instagram.com/web/search/topsearch/?query=${username}`
    );

    const userQueryJson = await userQueryRes.json();

    const userId = userQueryJson.users.map(u => u.user)
                                      .filter(
                                        u => u.username === username
                                       )[0].pk;

    let after = null;
    let 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 });

    after = null;
    has_next = true;

    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 });

    dontFollowMeBack = followings.filter((following) => {
      return !followers.find(
        (follower) => follower.username === following.username
      );
    });

    console.log({ dontFollowMeBack });

    iDontFollowBack = followers.filter((follower) => {
      return !followings.find(
        (following) => following.username === follower.username
      );
    });

    console.log({ iDontFollowBack });

    console.log(
      `Process is done: Type 'copy(followers)' or 'copy(followings)' or 'copy(dontFollowMeBack)' or 'copy(iDontFollowBack)' in the console and paste it into a text editor to take a look at it'`
    );
  } catch (err) {
    console.log({ err });
  }
})();
Run Code Online (Sandbox Code Playgroud)

  • 这真的很好,并且在 01/2023 仍然有效 (8认同)
  • @Bruno,您可以尝试直接对答案提出编辑建议,而不是使用评论 (3认同)
  • 知道如何按时间顺序对这些列表进行排序吗? (2认同)

Mar*_*ägi 31

湿婆的回答不再适用.Instagram不支持API调用" / users/{user-id}/follow "一段时间(2016年被禁用).

有一段时间你只能通过"/ users/self/follow"端点获得你自己的粉丝/ 粉丝,但是Instagram在2018年4月禁用了该功能(带有Cambridge Analytica问题).你可以在这里阅读它.

据我所知(目前),没有可用的服务(官方或非官方),您可以获得用户的关注者/关注者(甚至是您自己的).

  • 有许多 iOS 应用程序显示用户/关注者。我阅读了 Instagram 开发者文档上的权限文档。关注者请求已被弃用。但 App Store 应用程序如何仍然显示关注者呢?我不明白。有谁知道 ? (5认同)
  • 此 api 用于获取自己的关注者/关注列表:`https://api.instagram.com/v1/users/self/follows?access_token=ACCESS-TOKEN` (2认同)
  • @MarkoSulamägi 我尝试对这些应用程序进行逆向工程,我发现他们正在使用这个(https://github.com/charlieAndroidDev/Instagram4Android)我能够通过这个获得关注者列表我没有检查他们是如何获得的,但是这不是官方api (2认同)

Cai*_*ris 25

这是一种仅使用浏览器和一些复制粘贴即可获取用户关注的人员列表的方法(基于 Deep Seeker 答案的纯 JavaScript 解决方案):

  1. 获取用户的 id(在浏览器中,导航到https://www.instagram.com/user_name/?__a=1并寻找 response -> graphql -> user -> id [来自 Deep Seeker 的回答])

  2. 打开另一个浏览器窗口

  3. 打开浏览器控制台并将其粘贴到其中

    options = {
        userId: your_user_id,
        list: 1 //1 for following, 2 for followers
    }
    Run Code Online (Sandbox Code Playgroud)

  4. 更改为您的用户 ID 并按 Enter

  5. 将此粘贴到控制台中并按 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
        }))
    Run Code Online (Sandbox Code Playgroud)

  6. 导航到输出的链接

(这会为 http 请求设置标头。如果您尝试在未打开的页面上运行脚本,它将无法工作。)

  1. 在您刚刚打开的页面的控制台中,粘贴此内容并按 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);
    }
    Run Code Online (Sandbox Code Playgroud)

几秒钟后,它应该输出您的用户正在关注的用户列表。

编辑 3/12/2021

故障排除

如果您收到未兑现的承诺,请仔细检查这些事项

  • 确保您已登录 Instagram(用户12857969 的回答
  • 确保您未处于隐身模式或以其他方式阻止 Instagram 验证您的登录信息。
  • 确保您尝试访问其信息的帐户是公开的,或者他们允许您关注他们。

检查问题的一种方法是确保您在步骤 6 中导航到的页面有数据。如果看起来如下所示,那么您要么未登录,该用户是私人用户且您无权查看他们的关注者/关注者,要么您的浏览器不允许使用 cookie 且 Instagram 无法确认您的身份:

{"data":{"user":{"edge_followed_by":{"count":196,"page_info":{"has_next_page":false,"end_cursor":null},"edges":[]},"edge_mutual_followed_by":{"count":0,"edges":[]}}},"status":"ok"}
Run Code Online (Sandbox Code Playgroud)

  • 当我在 chrome 中执行此操作时,出现错误:“Uncaught ReferenceError: options is not Define at <anonymous>:58:1 (anonymous) @ VM69:58” (2认同)
  • 我在控制台中再次复制了第 6 步中的“选项”。运行脚本返回 Promise 数据响应,然后返回我关注的帐户列表。 (2认同)

Shi*_*iva 14

您可以使用以下Instagram API端点来获取用户关注的人员列表.

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

这是该端点的完整文档.GET /用户/用户ID /如下

这是执行该端点的示例响应. 在此输入图像描述

由于此端点需要user-id(而不是user-name),具体取决于您编写API客户端的方式,您可能必须使用用户名调用/ users/search端点,然后从响应中获取用户ID,将其传递给上面的/users/user-id/follows端点以获取关注者列表.

IANAL,但考虑到它在API中的记录,并查看使用条款,我不明白这是不合法的.

  • 这已经完全过时了。 (8认同)
  • 是的,截至2016年6月1日.现在您只能获得自己的关注者/关注者列表. (5认同)
  • 由于此端点已停用,因此无效 (4认同)
  • 那时Instagram APi没有瘫痪.它在2016年6月开始瘫痪. (2认同)

Chh*_*eng 14

我根据凯特琳·莫里斯(Caitlin Morris)在 Instagram 上获取所有关注者和关注者的回答,开创了自己的道路。只需复制此代码,粘贴到浏览器控制台并等待几秒钟。

您需要使用instagram.com选项卡中的浏览器控制台才能使其正常工作。

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')
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您需要的话,您还可以在登录时使用“window._sharedData.config.viewer.id”来获取当前用户 ID。 (3认同)
  • 通过更多分析(不关注我的人/我不关注的人)对其进行了调整,并且考虑到我遇到了问题,还更改了用户 ID 的方法。这是新版本:https://gist.github.com/Jeandcc/3c05d6104e94ded9884f4e39880d1be3 (3认同)
  • 它给出了一个错误 - Uncaught SyntaxError:await 仅在异步函数和异步生成器中有效 (2认同)
  • @user3191334 是的兄弟,它仍然有效。您需要在浏览器中打开 instagram.com,然后从该浏览器选项卡中打开开发人员工具。然后,只需将此代码粘贴到控制台中即可。 (2认同)
  • 它适用于铬。不是火狐浏览器 (2认同)

小智 7

过去几天我一直在为 chrome 开发一些 Instagram 扩展,我得到了这个锻炼:

首先,您需要知道如果用户个人资料是公开的或者您已登录并且您正在关注该用户,则这可以工作。

我不确定为什么它会这样工作,但可能在您登录时设置了一些 cookie,并在获取私人配置文件时在后端检查这些 cookie。

现在我将与您分享一个 ajax 示例,但如果您不使用 jquery,您可以找到其他更适合您的示例。

此外,您可以注意到我们有两个 query_hash 值用于关注者和关注者以及其他查询不同的值。

let config = {
  followers: {
    hash: 'c76146de99bb02f6415203be841dd25a',
    path: 'edge_followed_by'
  },
  followings: {
    hash: 'd04b0a864b4b54837c0d870b0e77e076',
    path: 'edge_follow'
  }
};
Run Code Online (Sandbox Code Playgroud)

你可以从用户IDhttps://www.instagram.com/user_name/?__a=1response.graphql.user.id

之后只是您收到的第一部分用户的响应,因为每个请求限制为 50 个用户:

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);
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

您可能可以在 Instagram 网站之外使用它,但我没有尝试过,您可能需要一些标题来匹配 Instagram 页面上的标题。

如果您需要这些标头的一些额外数据,您可能会在window._sharedData来自后端的带有 csrf 令牌等的 JSON 中找到这些数据。

您可以使用以下方法捕获此问题:

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

那都是我的!

希望能帮到你!


归档时间:

查看次数:

79039 次

最近记录:

6 年,3 月 前