Python Facebook API - 光标分页

Python Facebook API - cursor pagination

我的问题涉及学习如何使用 Facebook 的 Python API 检索我的整个好友列表。 当前结果returns一个好友数量有限的对象和一个link到'next'页面。我如何使用它来获取下一组朋友?(请 post 和 link 到可能的重复)任何帮助将不胜感激。一般来说,我需要了解 API 用法所涉及的分页。

import facebook
import json

ACCESS_TOKEN = "my_token"

g = facebook.GraphAPI(ACCESS_TOKEN)

print json.dumps(g.get_connections("me","friends"),indent=1)

遗憾的是分页文档是一个悬而未决的问题since almost 2 years. You should be able to paginate like this (based on this example) using requests:

import facebook
import requests

ACCESS_TOKEN = "my_token"
graph = facebook.GraphAPI(ACCESS_TOKEN)
friends = graph.get_connections("me","friends")

allfriends = []

# Wrap this block in a while loop so we can keep paginating requests until
# finished.
while(True):
    try:
        for friend in friends['data']:
            allfriends.append(friend['name'].encode('utf-8'))
        # Attempt to make a request to the next page of data, if it exists.
        friends=requests.get(friends['paging']['next']).json()
    except KeyError:
        # When there are no more pages (['paging']['next']), break from the
        # loop and end the script.
        break
print allfriends

更新: 有一个新的生成器方法可用,它实现了上述行为,可用于像这样迭代所有朋友:

for friend in graph.get_all_connections("me", "friends"):
    # Do something with this friend.

同时我在这里搜索答案是更好的方法:

import facebook
access_token = ""
graph = facebook.GraphAPI(access_token = access_token)

totalFriends = []
friends = graph.get_connections("me", "/friends&summary=1")

while 'paging' in friends:
    for i in friends['data']:
        totalFriends.append(i['id'])
    friends = graph.get_connections("me", "/friends&summary=1&after=" + friends['paging']['cursors']['after'])

在结束点,您会得到一个响应,其中数据为空,然后将没有 'paging' 键,因此那时它会中断,所有数据都将被存储。

在此示例中,您一次将设置/分页偏移一个,我认为我的 while 循环很简单,因为它只查找分页键 "next" 是否为 none,如果不存在意味着我们完成循环,您将在列表中获得结果。 在这个例子中,我只是在寻找所有叫 jacob

的人
import requests
import facebook

token = access_token="your token goes here"
fb = facebook.GraphAPI(access_token=token)
limit = 1
offset = 0
data = {"q": "jacob",
        "type": "user",
        "fields": "id",
        "limit": limit,
        "offset": offset}
req = fb.request('/search', args=data, method='GET')

users = []
for item in req['data']:
    users.append(item["id"])

pag = req['paging']
while pag.get("next") is not None:
    offset += limit
    data["offset"] = offset
    req = fb.request('/search', args=data, method='GET')
    for item in req['data']:
        users.append(item["id"])
    pag = req.get('paging')
print users
I couldn't find this anywhere, these answers seem super complicated and just no way I would even use an SDK if I had do stuff like that when Paging from a simple POST is so easy to start with, however: 

FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)

my_account = AdAccount('act_23423423423423423')


# In the below, I added the limit to the max rows, 250. 
# Also more importantly, paging. the SDK has a really sneaky way of doing this,
# enclose the request in a list() the results end up the same, but this will make the script request new objects until there are no more
#I tested this example and compared to Graph API and as of right now, 1/22 9:47AM, I get 81 from Graph and 81 here. 
fields = ['name']
params = {'limit':250}
ads = list(my_account.get_ads(
           fields = fields,
           params = params,
      ))

文档中的技巧:“注意:我们用 list() 包装 get_ad_accounts 的 return 值,因为 get_ad_accounts return 是一个 EdgeIterator 对象(位于facebook_business.adobjects),我们希望立即获得完整列表,而不是让迭代器延迟加载帐户。"

https://github.com/facebook/facebook-python-business-sdk