需要用facebook.py列出所有好友
我在使用 facebook.py,来自这个链接:https://github.com/pythonforfacebook/facebook-sdk
我遇到的问题是:我不知道怎么使用 graph.get_object("me/friends") 返回的下一个网址(next-url)。
graph = facebook.GraphAPI(access_token)
friends = graph.get_object("me/friends")
2 个回答
2
上面的回答有点误导,因为Facebook已经关闭了graph
接口,用户无法获取朋友列表,除非这些朋友也安装了这个应用。
请看:
graph = facebook.GraphAPI( token )
friends = graph.get_object("me/friends")
if friends['data']:
for friend in friends['data']:
print ("{0} has id {1}".format(friend['name'].encode('utf-8'), friend['id']))
else:
print('NO FRIENDS LIST')
4
如果你在 Graph API Explorer 中输入 /me/friends
,你会看到它返回一个JSON文件。这个文件其实就是一些字典和列表相互嵌套在一起的组合。
比如,输出可能是这样的:
{
"data": [
{
"name": "Foo",
"id": "1"
},
{
"name": "Bar",
"id": "1"
}
],
"paging": {
"next": "some_link"
}
}
这个JSON文件已经被转换成了Python中的字典和列表。在最外层的字典中,data
这个键对应的是一个字典列表,这些字典里包含了你朋友的信息。
所以,如果你想打印出你的朋友列表,可以这样做:
graph = facebook.GraphAPI(access_token)
friends = graph.get_object("me/friends")
for friend in friends['data']:
print "{0} has id {1}".format(friend['name'].encode('utf-8'), friend['id'])
这里的 .encode('utf-8')
是为了正确显示一些特殊字符。