【问题标题】:Python Facebook API - cursor paginationPython Facebook API - 光标分页
【发布时间】:2015-04-19 18:52:07
【问题描述】:

我的问题涉及学习如何使用 Facebook 的 Python API 检索我的整个朋友列表。 当前结果返回一个朋友数量有限的对象和一个指向“下一页”的链接。我如何使用它来获取下一组朋友?(请发布可能重复的链接)任何帮助将不胜感激。一般来说,我需要了解涉及到 API 使用的分页。

import facebook
import json

ACCESS_TOKEN = "my_token"

g = facebook.GraphAPI(ACCESS_TOKEN)

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

【问题讨论】:

    标签: python facebook pagination


    【解决方案1】:
    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 的返回值,因为 get_ad_accounts 返回一个 EdgeIterator 对象(位于 facebook_business.adobjects 中),我们希望立即获取完整列表,而不是使用迭代器延迟加载帐户。”

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

    【讨论】:

      【解决方案2】:

      遗憾的是,分页文档是一个未解决的问题since almost 2 years。您应该可以使用requests 像这样(基于this example)进行分页:

      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.
      

      【讨论】:

      • 为什么?你必须给我更多。
      • 对不起!实际上,第二个请求 "" requests.get(friends['paging']['next']).json() "" 返回一个对象,friends['data'] 为空列表
      • 有错误吗?这个对我有用。另一方面:您应该检查Graph API explorer,如果它返回您想要的数据。如果不是,那可能与分页无关,而是其他原因。
      • 不是错误。只是显示只有第一组朋友!我只是无法弄清楚为什么
      • 这可能是因为您的 URL 中的“直到”参数。删除它后,一切都会正常。
      【解决方案3】:

      在此示例中,您一次将 set / pagination 偏移一个,我认为我的 while 循环很简单,因为它只寻找分页键“next”为无,如果不存在意味着我们完成循环,您将将您的结果列在列表中。 在这个例子中,我只是在寻找所有叫 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
      

      【讨论】:

        【解决方案4】:

        同时我在这里寻找答案是更好的方法:

        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'])
        

        在结束时,您将收到一个响应,其中数据将为空,然后将没有“分页”键,因此届时它将中断并存储所有数据。

        【讨论】:

        • 收到错误facebook.GraphAPIError: Unknown path components: /friends&after=Q
        • @kirankumarkotari 嗨,您可以在我编辑过的路径上输入/ 后尝试一下,看看它是否正常工作。
        • 这不起作用。 friends = graph.get_connections("me", "/friends&summary=1") 返回与 graph.get_object('me') 相同
        猜你喜欢
        • 2017-08-16
        • 2015-07-06
        • 2019-09-08
        • 2021-06-02
        • 2013-06-18
        • 2012-12-03
        • 1970-01-01
        • 2016-10-13
        • 2018-03-01
        相关资源
        最近更新 更多