Python:Facebook Graph API - 使用 facebook-sdk 的分页请求

2024-04-28

我正在尝试向 Facebook 查询不同的信息,例如 - 好友列表。它工作得很好,但当然它只能给出有限数量的结果。如何获取下一批结果?

import facebook
import json

ACCESS_TOKEN = ''

def pp(o):
    with open('facebook.txt', 'a') as f:
        json.dump(o, f, indent=4)


g = facebook.GraphAPI(ACCESS_TOKEN)
pp(g.get_connections('me', 'friends'))

结果 JSON 确实给了我 paging-cursors-before 和 after 值 - 但我该把它放在哪里呢?


我正在通过以下方式探索 Facebook Graph APIfacepyPython 库(也适用于 Python 3),但我想我可以提供帮助。

TL-DR:

您需要附加&after=YOUR_AFTER_CODE到您调用的 URL(例如:https://graph.facebook/v2.8/YOUR_FB_ID/friends/?fields=id,name),给你一个像这样的链接:https://graph.facebook/v2.8/YOUR_FB_ID/friends/?fields=id,name&after=YOUR_AFTER_CODE,您应该发出 GET 请求。


你需要requests为了使用您的用户 ID(我假设您知道如何以编程方式找到它)和一些类似于我在下面给您的 URL 发出对 Graph API 的 get 请求(请参阅URL多变的)。

import facebook
import json
import requests

ACCESS_TOKEN = ''
YOUR_FB_ID=''
URL="https://graph.facebook.com/v2.8/{}/friends?access_token={}&fields=id,name&limit=50&after=".format(YOUR_FB_ID, ACCESS_TOKEN)

def pp(o):
    all_friends = []
    if ('data' in o):
        for friend in o:
            if ('next' in friend['paging']):
                resp = request.get(friend['paging']['next'])
                all_friends.append(resp.json())
            elif ('after' in friend['paging']['cursors']):
                new_url = URL + friend['paging']['cursors']['after']
                resp = request.get(new_url)
                all_friends.append(resp.json())
             else:
                 print("Something went wrong")
             
    # Do whatever you want with all_friends...
    with open('facebook.txt', 'a') as f:
        json.dump(o, f, indent=4)


g = facebook.GraphAPI(ACCESS_TOKEN)
pp(g.get_connections('me', 'friends'))

希望这可以帮助!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python:Facebook Graph API - 使用 facebook-sdk 的分页请求 的相关文章

随机推荐