我的问题涉及学习如何使用 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)
遗憾的是,分页文档是一个悬而未决的问题近两年以来 https://github.com/pythonforfacebook/facebook-sdk/issues/85。你应该能够像这样分页(基于这个例子 https://github.com/pythonforfacebook/facebook-sdk/commit/6169cae69949eb8948268b15c2dc21862b5cb7d8) using requests http://docs.python-requests.org/en/latest/user/install/:
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:有一个新的生成器方法可用,它实现上述行为,并可用于迭代所有友元,如下所示:
for friend in graph.get_all_connections("me", "friends"):
# Do something with this friend.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)