如何导出个人网站多页面的Facebook评论至CSV/Excel文件?
Got it, let's figure out how to export those per-page Facebook comments from your website into CSV/Excel using Python. I've broken this down into straightforward steps so you can follow along easily:
1. First: Set Up Facebook Graph API Access
To pull comments via Python, you'll need to use the Facebook Graph API. Here's what you need to do:
- Go to the Facebook for Developers portal and create a new app (choose "Business" or "Consumer" depending on your use case).
- Head to the Graph API Explorer tool, select your new app, and generate a user access token. Make sure to request permissions like
pages_read_engagement(for accessing comments linked to your website) andpublic_profile. - Note down this access token—you'll need it in your Python script.
2. Install Required Python Libraries
You'll need two key libraries: requests to call the API, and pandas to handle data and export to CSV/Excel. Install them with this command:
pip install requests pandas openpyxl
(openpyxl is needed for Excel export)
3. Python Script to Export Comments
This script will loop through all your website pages, fetch their associated Facebook comments, and export everything into CSV/Excel files.
import requests import pandas as pd import time # Configuration - fill these in! ACCESS_TOKEN = "YOUR_GENERATED_FACEBOOK_ACCESS_TOKEN" # List all your website page URLs here PAGE_URLS = [ "https://your-website.com/page-one", "https://your-website.com/page-two", "https://your-website.com/page-three", # Add more pages as needed ] # Define which comment fields to fetch (customize this if you want more data) COMMENT_FIELDS = "message,from{name,id},created_time,like_count,parent{id}" def fetch_comments_for_page(page_url): """Fetch all comments (including nested replies) for a single page URL""" all_comments = [] # Build the API endpoint api_endpoint = ( f"https://graph.facebook.com/v18.0/?id={page_url}" f"&fields=comments{{{COMMENT_FIELDS}}}" f"&access_token={ACCESS_TOKEN}" ) while api_endpoint: try: response = requests.get(api_endpoint) response.raise_for_status() # Raise error for HTTP issues data = response.json() if "error" in data: print(f"❌ Error fetching comments for {page_url}: {data['error']['message']}") break # Extract comments if they exist if "comments" in data and "data" in data["comments"]: for comment in data["comments"]["data"]: comment_entry = { "page_url": page_url, "comment_id": comment["id"], "author_name": comment["from"]["name"], "author_id": comment["from"]["id"], "comment_text": comment.get("message", ""), "created_time": comment["created_time"], "like_count": comment.get("like_count", 0), "parent_comment_id": comment.get("parent", {}).get("id", None) } all_comments.append(comment_entry) # Move to next page of comments (if available) api_endpoint = data["comments"].get("paging", {}).get("next") # Add a small delay to avoid hitting API rate limits if api_endpoint: time.sleep(1) except requests.exceptions.RequestException as e: print(f"⚠️ Request failed for {page_url}: {str(e)}") break return all_comments # Collect comments from all pages print("🔍 Starting to fetch comments across all pages...") total_comments = [] for url in PAGE_URLS: print(f"Processing {url}...") page_comments = fetch_comments_for_page(url) total_comments.extend(page_comments) print(f"✅ Found {len(page_comments)} comments for this page") # Export to CSV and Excel if total_comments: df = pd.DataFrame(total_comments) # Export to CSV (UTF-8 encoded to handle special characters) df.to_csv("facebook_website_comments.csv", index=False, encoding="utf-8-sig") # Export to Excel df.to_excel("facebook_website_comments.xlsx", index=False) print(f"\n🎉 Done! Exported {len(total_comments)} comments to CSV and Excel files.") else: print("\nℹ️ No comments found to export.")
4. Key Notes to Keep in Mind
- Access Token Validity: User access tokens expire after a short time. For long-term use, you can generate a long-lived token (via the Graph API) or use a page access token if your comments are linked to a Facebook Page.
- Rate Limits: Facebook's API has rate limits—adding the
time.sleep(1)delay helps avoid hitting them. If you get 429 errors, increase the delay or batch your requests. - Nested Replies: The script fetches parent comment IDs, so you can map replies to their original comments in your CSV/Excel.
- Permission Checks: If you're getting "permission denied" errors, double-check that your access token has the right permissions, and that your app is linked to your website (add your domain to the app's "Settings > Basic" section).
内容的提问来源于stack exchange,提问作者The Deepest Sleep
相关产品推荐
相关产品推荐

