先决条件:Facebook API |组 1、组 2
在本文中,我们将讨论三种方法:
- 搜索
- 获取连接
- 获取所有连接
search
方法:
有效的值类型是 place 和 placetopic。
Parameters:
id: It is a string containing a valid value.
args: This is optional and they need to passed a query params.
示例:获取德里康诺特广场附近所有地点的详细信息。康诺特广场的纬度和经度是 – 28.6304, 77.2177
import json
import facebook
def main():
token = "Please replace with your access token"
graph = facebook.GraphAPI(token)
places = graph.search(type ='place', center ='28.6304, 77.2177',
fields ='name, location')
for place in places['data']:
print('%s %s' %(place['name'].encode(), place['location'].get('zip')))
if __name__ == '__main__':
main()
有关可以使用的字段的完整列表,请参阅链接搜索参考。
get_connections
方法:
此方法旨在返回所有连接,或者我们可以将提到的对象的 Edges 称为dict 。
Parameters:
id:A string specifying the unique id for the resource under question.
connection name: A string specifying the connection or edges between the objects.
如果连接名称参数为空,则get_connections
方法将简单地返回已验证用户的基本信息。
示例#1:我们想找出活跃用户的好友总数。
import json
import facebook
def main():
token = "Please replace this with your access token"
graph = facebook.GraphAPI(token)
friends = graph.get_connections(id ='me', connection_name ='friends')
print(json.dumps(friends, indent = 4))
if __name__ == '__main__':
main()
示例#2:我们想要从页面中获取所有帖子的列表。为此,我们将使用 get_connections,稍后我们将演示如何使用get_all_connections
方法。
import json
import facebook
def main():
token = "Please replace this with your PAGE Access Token"
graph = facebook.GraphAPI(token)
posts_25 = graph.get_connections(id ='PAGE_ID', connection_name ='posts',
fields ='id, created_time')
print(json.dumps(posts_25, indent = 4))
if __name__ == '__main__':
main()
注意:这个例子默认打印最新的 25 个帖子。您可以使用 limit(…) 为帖子添加过滤器以设置帖子数量的限制。
例3:在这个例子中,我们将使用get_connections方法打印在帖子所有评论reverse_chronological
顺序,显示子评论,包括隐藏的意见,但也显示出评论的总数。
import json
import facebook
def main():
token = "Please replace this with your PAGE Access Token"
graph = facebook.GraphAPI(token)
posts_25 = graph.get_connections(id ='POST_ID', connection_name ='comments',
include_hidden = True, order ='reverse_chronological',
filter ='stream', summary ='total_count')
print(json.dumps(posts_25, indent = 4))
if __name__ == '__main__':
main()
get_all_connections
方法:
遍历 get_connections 调用返回的所有页面并生成单个项目。
Parameters:
id:A string specifying the unique id for the resource under question.
connection name: A string specifying the connection or edges between the objects.
示例 #1:在本示例中,我使用 get_all_connections 列出了使用自日期时间参数列出的页面中的所有帖子。
import json
import facebook
from datetime import datetime
def main():
token = "Please replace this with your PAGE Access Token"
graph = facebook.GraphAPI(token)
posts_all = graph.get_all_connections(id ='PAGE_ID', connection_name ='posts',
fields ='created_time, id',
since = datetime(2017, 1, 1, 0, 0, 0))
for ind, post in enumerate(posts_all):
print(json.dumps(ind, indent = 4))
print(json.dumps(post, indent = 4))
if __name__ == '__main__':
main()
参考:
- https://developers.facebook.com/docs/marketing-api/insights/parameters
- https://developers.facebook.com/docs/graph-api/