杰瑞科技汇

python Facebook api

Of course! Using the Facebook API with Python is a common task, but it's important to understand that the "Facebook API" is now part of a larger ecosystem called the Meta API. The core principles and libraries remain the same.

python Facebook api-图1
(图片来源网络,侵删)

This guide will walk you through the most common use case: accessing the Graph API to read data from a Facebook Page or Group.

We'll cover:

  1. Prerequisites: What you need before you start coding.
  2. Choosing a Library: facebook-sdk vs. facebook-business.
  3. Example 1: Using facebook-sdk for simple Graph API calls.
  4. Example 2: Using facebook-business for Ads, Pages, and more advanced features.
  5. Key Concepts: Access Tokens, Permissions, and API Versions.

Prerequisites: Setting Up Your App

You cannot use the API without first registering an application with Meta. This process gives you the necessary credentials.

  1. Go to the Meta for Developers Portal: https://developers.facebook.com/
  2. Log in with your personal Facebook account.
  3. Create a New App:
    • Click the "My Apps" dropdown and select "Add New App".
    • Choose a platform (e.g., "Business").
    • Give your app a name (e.g., "My Python Data Scraper") and click "Create App ID".
  4. Get Your App Credentials:
    • Once your app is created, go to the Dashboard.
    • You will see your App ID and App Secret. Treat your App Secret like a password! Do not expose it in client-side code.
  5. Add a Product:
    • In the left-hand menu, click on "Products".
    • Find and select "Graph API".
    • Click "Set Up".
  6. Request User Permissions:
    • You need to ask the user for permission to access their data. For a Page, you'll need the pages_read_engagement permission.
    • To get this, you need to create a Facebook Login product.
    • Go to "Products" -> "Facebook Login" -> "Settings".
    • Under "Valid OAuth Redirect URIs", you can put a placeholder like https://localhost:8000 for local development.
  7. Generate an Access Token:
    • This is the most crucial step. The token proves your app is authorized to act on a user's behalf.
    • The easiest way to get a token for testing is the Graph API Explorer.
    • In the top right, select your App.
    • Click "Get User Access Token".
    • A dialog box will appear. Check the box for pages_read_engagement (or whatever permission you need).
    • Click "Get Access Token" and then "Got it" on the next screen.
    • The generated token in the text box is what you'll use in your Python script. Note that this token will expire in about an hour. For a real application, you would implement a login flow to get a long-lived token.

Choosing a Python Library

Meta provides official and community-supported SDKs. The two most popular for Python are:

python Facebook api-图2
(图片来源网络,侵删)
Library Best For Pros Cons
facebook-sdk Simple Graph API calls (reading posts, comments, etc.). Lightweight, easy to start, great for basic data retrieval. Less actively maintained, doesn't cover newer API features like Instagram or advanced Ads management.
facebook-business Ads, Business Management, advanced Page/Instagram management. Officially supported by Meta, feature-rich, excellent documentation. More complex, has more dependencies, can be overkill for simple tasks.

Recommendation: Start with facebook-sdk for simple data reading. If you need to manage Ads or use more complex features, use facebook-business.


Example 1: Using facebook-sdk for Simple Data

This example will fetch the posts from a public Facebook Page.

Step 1: Install the library

pip install facebook-sdk

Step 2: Write the Python script

python Facebook api-图3
(图片来源网络,侵删)

Replace YOUR_ACCESS_TOKEN with the token you got from the Graph API Explorer. Replace PAGE_ID with the ID or username of the public page you want to scrape (e.g., Nike).

import facebook
import requests
# --- Configuration ---
# Replace with your App ID and App Secret if you need to get a new token
# APP_ID = 'YOUR_APP_ID'
# APP_SECRET = 'YOUR_APP_SECRET'
# Replace with your User Access Token from the Graph API Explorer
ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN' 
# Replace with the ID or username of the public Page
PAGE_ID = 'Nike' 
# The Graph API version to use (Meta recommends using a recent version)
API_VERSION = 'v18.0'
def get_facebook_posts(page_id, access_token):
    """
    Fetches posts from a public Facebook Page using the Graph API.
    """
    try:
        # Initialize the Graph API connection
        # We don't need app secret for reading public data with a valid user token
        graph = facebook.GraphAPI(access_token=access_token, version=API_VERSION)
        # Make the API request
        # The 'fields' parameter specifies what data we want to receive
        posts = graph.get_object(
            id=page_id,
            fields='id,message,created_time,permalink_url,likes.summary(true),comments.summary(true)'
        )
        print(f"Successfully fetched posts for {page_id}.")
        return posts.get('data', [])
    except facebook.GraphAPIError as e:
        print(f"Graph API Error: {e.type} - {e.message}")
        return None
    except requests.exceptions.RequestException as e:
        print(f"Request Error: {e}")
        return None
def print_posts(posts):
    """Prints the fetched posts in a readable format."""
    if not posts:
        print("No posts found.")
        return
    for post in posts:
        print("-" * 50)
        print(f"Post ID: {post['id']}")
        print(f"Created: {post['created_time']}")
        print(f"Link: {post.get('permalink_url', 'N/A')}")
        if 'message' in post:
            print(f"Message:\n{post['message']}")
        likes_count = post.get('likes', {}).get('summary', {}).get('total_count', 0)
        comments_count = post.get('comments', {}).get('summary', {}).get('total_count', 0)
        print(f"Likes: {likes_count}")
        print(f"Comments: {comments_count}")
        print("-" * 50)
if __name__ == "__main__":
    all_posts = get_facebook_posts(PAGE_ID, ACCESS_TOKEN)
    if all_posts:
        print_posts(all_posts)

To Run:

  1. Fill in your ACCESS_TOKEN and PAGE_ID.
  2. Save the code as fb_scraper.py.
  3. Run from your terminal: python fb_scraper.py

Example 2: Using facebook-business (Ads API)

This library requires a different kind of token: a System User token. This is designed for server-to-server communication and doesn't expire as quickly.

Prerequisites for this example:

  1. In your App's settings, you need to add a "System User" under "Roles".
  2. Assign this System User a role in your Facebook Business Manager (e.g., "Admin" on the Ad Account or Page you want to access).
  3. Generate a long-lived System User Access Token for this user.

Step 1: Install the library

pip install facebook-business

Step 2: Write the Python script

This example fetches Ad Campaigns from an Ad Account.

from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.campaign import Campaign
# --- Configuration ---
# Replace with your App ID and App Secret
APP_ID = 'YOUR_APP_ID'
APP_SECRET = 'YOUR_APP_SECRET'
# Replace with your System User Access Token
SYSTEM_USER_ACCESS_TOKEN = 'YOUR_SYSTEM_USER_ACCESS_TOKEN'
# Replace with your Ad Account ID (format: act_XXXXXX)
AD_ACCOUNT_ID = 'act_XXXXXX' 
# Initialize the API
FacebookAdsApi.init(
    app_id=APP_ID,
    app_secret=APP_SECRET,
    access_token=SYSTEM_USER_ACCESS_TOKEN,
    # api_version='v18.0' # Specify version if needed
)
def get_ad_campaigns(ad_account_id):
    """
    Fetches ad campaigns from a specified Ad Account.
    """
    try:
        # Get the AdAccount object
        account = AdAccount(ad_account_id)
        # Get the campaigns
        # The 'fields' parameter specifies what data we want
        campaigns = account.get_campaigns(
            fields=[
                Campaign.Field.name,
                Campaign.Field.status,
                Campaign.Field.daily_budget,
                Campaign.Field.spend,
            ]
        )
        print(f"Successfully fetched campaigns for Ad Account {ad_account_id}.")
        return campaigns
    except Exception as e:
        print(f"An error occurred: {e}")
        return None
def print_campaigns(campaigns):
    """Prints the fetched campaigns."""
    if not campaigns:
        print("No campaigns found.")
        return
    for campaign in campaigns:
        print("-" * 50)
        print(f"Campaign ID: {campaign['id']}")
        print(f"Name: {campaign['name']}")
        print(f"Status: {campaign['status']}")
        print(f"Daily Budget: {campaign['daily_budget']}")
        print(f"Spend: {campaign['spend']}")
        print("-" * 50)
if __name__ == "__main__":
    all_campaigns = get_ad_campaigns(AD_ACCOUNT_ID)
    if all_campaigns:
        print_campaigns(all_campaigns)

Key Concepts to Remember

  • Access Token: The "key" that allows your app to access the API. It has permissions and an expiration date.
    • User Token: For acting on behalf of a Facebook user. Needs to be obtained via a login flow.
    • Page Token: A special user token that has been granted permissions to manage a specific Page.
    • System User Token: For server-to-server access, managed within Business Manager. More stable for automation.
  • Permissions (Scopes): You must request specific permissions (e.g., pages_read_engagement, ads_management) from the user or assign them to a System User.
  • API Version: The Graph API is constantly updated. You must specify an API version (e.g., v18.0) in your requests. Meta deprecates old versions, so using a recent one is crucial for long-term stability. The default version in the libraries might change, so it's good practice to be explicit.
  • Rate Limits: The API limits how many requests you can make in a given time period. If you hit the limit, you'll have to wait before making more requests. Check the Rate Limiting documentation.
分享:
扫描分享到社交APP
上一篇
下一篇