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

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

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

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

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

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

这是该端点的完整文档。 GET/users/user-id/follows

这是执行该端点的示例响应。

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

IANAL,但考虑到它在他们的 API 中有记录,并查看使用条款,我不明白这样做有什么不合法的。

Shiva 的回答不再适用。 Instagram 一段时间内不支持 API 调用“/users/{user-id}/follows”(已在 2016 年禁用)。

有一段时间你只能通过 "/users/self/follows" 端点获得你自己的 followers/followings,但 Instagram 在 2018 年 4 月禁用了该功能(与 Cambridge Analytica 问题)。你可以 read about it here.

据我所知(目前)没有可用的服务(官方或非官方),您可以从中获得用户(甚至是您自己)的followers/followings。

您可以使用 Phantombuster。 Instagram 设置了一些速率限制,因此您将不得不使用多个帐户或等待 15 分钟以获取下一个 运行.

Instagram 的 REST API 已停产。但是您可以使用 GraphQL 来获取所需的数据。您可以在此处找到概览:https://developers.facebook.com/docs/instagram-api

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

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

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

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

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

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

您可以从 https://www.instagram.com/user_name/?__a=1 获取的用户 ID 为 response.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);
    }
  });
}

你可以在 Instagram 网站之外使用这个,但我没试过,你可能需要一些 headers 来匹配来自 instagram 页面的那些。

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

您可以使用以下方法捕获它:

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

这就是我的全部!

希望对您有所帮助!

这里有一种方法可以通过浏览器和一些 copy-paste(基于 Deep Seeker 的回答的纯 javascript 解决方案)获取用户正在关注的人员列表:

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

  2. 打开另一个浏览器window

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

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

  4. 更改为您的用户 ID 并按回车键

  5. 将其粘贴到控制台中并按回车键

    `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. 导航到输出的 link

(这会为 http 请求设置 headers。如果您尝试 运行 未打开的页面上的脚本,它将不起作用。)

  1. 在您刚打开的页面的控制台中,粘贴此内容并按回车键
    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);
    }
    

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

编辑 2021 年 3 月 12 日

疑难解答

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

  • 确保您已登录 Instagram (user12857969's answer)
  • 确保您没有处于隐身模式或以其他方式阻止 Instagram 验证您的登录信息。
  • 确保您尝试访问其信息的帐户是 public,或者他们允许您关注他们。

检查问题的一种方法是确保您在第 6 步中导航到的页面有数据。如果看起来像下面这样,那么你要么没有登录,用户是私人的,你无权查看他们的 follows/followers,要么你的浏览器不允许 cookies,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"}

我在 的基础上创建了自己的方法来获取 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')
}

还有另一种方法可以做到这一点。 Instapy 为我们提供了一组 API 用于执行此操作。

这是一个可用于此的简单代码。我们需要传递我们需要的 amount 的关注者,如果我们需要所有的关注者列表,我们需要传递 full 作为参数值数量。包含列表的文件将存储在本地。

只做一个简单的 pip 安装命令。

pip install instapy 

示例代码

from instapy import InstaPy

user = <Username>
password = <password>
gecko_path = <geckodriver path>
#instapy uses this internally
session = InstaPy(username=user, password=password,geckodriver_path= gecko_path)
session.login()
followers = session.grab_followers(username=user,amount=40)
print(followers)
following = session.grab_following(username=user,amount=40)
print(following)
session.end()

Link 到其文档:https://instapy.org/

https://i.instagram.com/api/v1/friendships/2/following/

其中 2 是感兴趣的用户 ID。它 returns 一个 json 用户 ID、用户名、全名、个人资料图片 URL 等列表。它需要一个 GET 参数 ?count=n 来限制响应。

如果你需要获得 IG 关注者,我认为最好的方法是在网络上登录 IG,然后从请求中获取 x-ig-app-idcookie,然后向此发送 GET 请求端点: https://i.instagram.com/api/v1/friendships/{userId}/following/?count=20&max_id=12

    {
        "users": [
            {
                "pk": 7385793727,
                "username": "nebitno",
                "full_name": "lela",
                "is_private": true,
                "profile_pic_url": "https://scontent-sof1-2.cdninstagram.com/v/t51.2885-19/s150x150/144485752_4993231520748255_75575875121006268732_n.jpg?cb=9ad74b5e-c1c39920&_nc_ht=scontent-sof1-2.cdninstagram.com&_nc_cat=103&_nc_ohc=956dXauIBogAX_zfWPW&edm=ALB854YBAAAA&ccb=7-4&oh=00_AT_EGZmL2bx-zMSBQqxYKUjIaYWVVyBnPH9__Y9jAccF0w&oe=61DFADB1&_nc_sid=04cb80",
                "profile_pic_id": "2500168216063422867_7385792727",
                "is_verified": false,
                "follow_friction_type": 0,
                "has_anonymous_profile_picture": false,
                "has_highlight_reels": false,
                "account_badges": [],
                "latest_reel_media": 1641496960,
                "is_favorite": false
            },
      ...
]}