Facebook Graph API是Facebook提供的一套RESTful API,允许开发者读取和写入Facebook社交图谱中的数据。通过这个API,可以获取用户、页面、帖子、评论等各种社交数据。
pages_read_engagement
等)import requests
import json
# 配置参数
access_token = 'YOUR_ACCESS_TOKEN'
page_id = 'PAGE_ID_OR_USERNAME'
fields = 'id,message,link,created_time' # 需要获取的字段
# 构建请求URL
url = f'https://graph.facebook.com/v12.0/{page_id}/posts'
params = {
'access_token': access_token,
'fields': fields,
'limit': 100 # 每次请求获取的帖子数量
}
# 发送请求
response = requests.get(url, params=params)
data = response.json()
# 处理返回数据
posts_with_links = []
for post in data.get('data', []):
if 'link' in post:
posts_with_links.append({
'id': post['id'],
'message': post.get('message', ''),
'link': post['link'],
'created_time': post['created_time']
})
# 输出结果
print(json.dumps(posts_with_links, indent=2))
Facebook API使用分页返回数据,可以使用next
字段获取下一页数据:
while 'paging' in data and 'next' in data['paging']:
next_url = data['paging']['next']
response = requests.get(next_url)
data = response.json()
for post in data.get('data', []):
if 'link' in post:
posts_with_links.append({
'id': post['id'],
'message': post.get('message', ''),
'link': post['link'],
'created_time': post['created_time']
})
pages_read_engagement
等必要权限message
字段中是否包含URL,可以使用正则表达式提取fields
参数精确控制返回的数据字段,提高效率since
和until
参数按时间范围筛选帖子/search
端点进行更复杂的搜索没有搜到相关的文章