Python:Facebook Graph API-使用facebook-sdk的分页请求 [英] Python: Facebook Graph API - pagination request using facebook-sdk

查看:88
本文介绍了Python:Facebook Graph API-使用facebook-sdk的分页请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向Facebook查询其他信息,例如-好友列表.它工作正常,但当然只能给出有限的结果.如何获得下一批结果?

I'm trying to query Facebook for different information, for example - friends list. And it works fine, but of course it only gives limited number of results. How do I access the next batch of results?

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确实给了我值之前和之后的分页游标-但是我应该放在哪里?

The result JSON does give me paging-cursors-before and after values - but where do I put it?

推荐答案

我正在通过facepy Python库(也适用于Python 3)探索Facebook Graph API.

I'm exploring Facebook Graph API through the facepy library for Python (works on Python 3 too), but I think I can help.

您需要将&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请求.

You need to append &after=YOUR_AFTER_CODE to the URL you've called (e.g: https://graph.facebook/v2.8/YOUR_FB_ID/friends/?fields=id,name), giving you a link like this one: https://graph.facebook/v2.8/YOUR_FB_ID/friends/?fields=id,name&after=YOUR_AFTER_CODE, that you should make a GET Request.

您需要requests,以便使用您的用户ID(我假设您知道如何以编程方式找到它)和一些类似于我在下面提供的网址的Graph API来获取对Graph API的请求. URL变量).

You'll need requests in order to make a get request for Graph API using your user ID (I'm assuming you know how to find it programatically) and some url similar to the one I give you below (see URL variable).

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

希望这会有所帮助!

这篇关于Python:Facebook Graph API-使用facebook-sdk的分页请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆