需要用facebook.py列出所有好友

2024-06-25 06:19:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用facebook.py来自: https://github.com/pythonforfacebook/facebook-sdk

我的问题是: 我不知道使用graph.get_object(“我/朋友”)中的下一个url

graph = facebook.GraphAPI(access_token)
friends = graph.get_object("me/friends")

Tags: pyhttpsgithubcomurlgetfacebookobject
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')

如果您在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')是正确打印特殊字符。

相关问题 更多 >