Exhibit 25.16 provides the code for retrieving Facebook posts and their comments using the Facebook Graph API and storing them in a MongoDB database. Here is a breakdown of the coding steps:
requests
for making HTTP requests to the Facebook Graph API and pymongo
for interacting with the MongoDB database
import requests
from pymongo import MongoClient
# Define Facebook Graph API Version
version = 'v2.13'
# Access Token (Replace with your actual token)
access_token = 'YOUR_ACCESS_TOKEN'
# Define Page ID
brand_id = '{brand_id}'
# Define Endpoints
page_url = f'https://graph.facebook.com/{version}/{brand_id}/feed?fields=id,message,reactions,shares,from,caption,created_time,likes.summary(true)'
comments_url = f'https://graph.facebook.com/{version}/{{post_id}}/comments?filter=stream&limit=100'
# Connect to MongoDB
client = MongoClient('localhost:27017')
db = client.facebook
collection_posts = db.posts
collection_comments = db.comments
params = {'access_token': access_token}
# Get the first page of posts
posts = requests.get(page_url, params=params).json()
# Loop through posts and their comments
while True:
try:
for element in posts['data']:
collection_posts.insert_one(element)
this_comment_url = comments_url.format(post_id=element['id'])
comments = requests.get(this_comment_url, params=params).json()
# Loop through comments using cursor for pagination
for comment in comments['data']:
comment['post_id'] = element['id']
collection_comments.insert_one(comment)
# Check for next page of comments
if 'paging' not in comments or 'next' not in comments['paging']:
break
comments = requests.get(comments['paging']['next'], params=params).json()
# Check for next page of posts
if 'paging' not in posts or 'next' not in posts['paging']:
break
posts = requests.get(posts['paging']['next'], params=params).json()
except Exception as e:
print(f"Error: {e}")
break
# Close connection
client.close()
Use the Search Bar to find content on MarketingMind.
Contact | Privacy Statement | Disclaimer: Opinions and views expressed on www.ashokcharan.com are the author’s personal views, and do not represent the official views of the National University of Singapore (NUS) or the NUS Business School | © Copyright 2013-2024 www.ashokcharan.com. All Rights Reserved.