Python Facebook API-游标分页 [英] Python Facebook API - cursor pagination
问题描述
我的问题涉及学习如何使用Facebook的Python API检索我的整个朋友列表. 当前结果返回一个对象,该对象的朋友数量有限,并具有指向下一个"页面的链接.我该如何使用它来获取下一组朋友?(请把链接发布到可能的重复项)任何帮助将不胜感激.通常,我需要了解涉及API使用的分页.
My question involves learning how to retrieve my entire list of friends using Facebook's Python API. The current result returns an object with limited number of friends and a link to the 'next' page. How do I use this to fetch the next set of friends ? (Please post the link to possible duplicates) Any help would be much appreciated. In general, I need to learn about the pagination involved the API usage.
import facebook
import json
ACCESS_TOKEN = "my_token"
g = facebook.GraphAPI(ACCESS_TOKEN)
print json.dumps(g.get_connections("me","friends"),indent=1)
推荐答案
遗憾的是,分页文档是一个未解决的问题将近两年了.您应该可以使用<(例如此示例)进行分页a href ="http://docs.python-requests.org/en/latest/user/install/" rel ="nofollow noreferrer">请求:
Sadly the documentation of pagination is an open issue 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
更新:有一个新的生成器方法可实现上述行为,并可用于遍历所有朋友,如下所示:
Update: There's a new generator method available which implements above behavior and can be used to iterate over all friends like this:
for friend in graph.get_all_connections("me", "friends"):
# Do something with this friend.
这篇关于Python Facebook API-游标分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!