facebook-scraper

repository·master·Indexed 25 days ago

https://github.com/kevinzg/facebook-scraper

A Python library and CLI tool for scraping public Facebook pages, profiles, and groups without requiring an official API key. It provides functionality to retrieve posts, comments, profile information, and group metadata, with support for exporting data to CSV or JSON. The library includes features for authentication via cookies or credentials, persistent sessions to avoid login flags, proxy and user-agent configuration, and specialized functions like get_posts, get_profile, and get_group_info.

Tokens
6.3K
Snippets
7
Records
54
Agent score
85%

What's inside facebook-scraper

  1. Download comments from a specific post

    master

    To download comments from a specific post, use get_posts with the post_urls parameter containing the POST_ID. You must use the options dictionary with the comments key to enable comment extraction.

    import facebook_scraper as fs
    
    # POST_ID can be extracted from URLs like:
    # https://www.facebook.com/USER/posts/POST_ID
    # https://www.facebook.com/groups/GROUP_ID/posts/POST_ID
    POST_ID = "pfbid02NsuAiBU9o1ouwBrw1vYAQ7khcVXvz8F8zMvkVat9UJ6uiwdgojgddQRLpXcVBqYbl"
    MAX_COMMENTS = 100
    
    # get_posts returns a generator
    gen = fs.get_posts(
        post_urls=[POST_ID],
        options={"comments": MAX_COMMENTS, "progress": True}
    )
    
    # Get the requested post
    post = next(gen)
    
    # Extract comments from 'comments_full'
    comments = post['comments_full']
    
    for comment in comments:
        print(comment)
        for reply in comment['replies']:
            print(' ', reply)
  2. Use get_posts to scrape posts

    master

    The get_posts function allows you to scrape posts from a unique page name, profile name, or ID. It returns a generator that yields post dictionaries.

    from facebook_scraper import get_posts
    
    for post in get_posts('nintendo', pages=1):
        print(post['text'][:50])
  3. Write posts directly to CSV or JSON with write_posts_to_csv

    master

    The write_posts_to_csv() function allows you to scrape posts and save them directly to disk. This is recommended for large-scale scraping as it saves data continuously and supports resuming from the last successful page.

    Key Parameters:

    • group: The ID or name of the group (uses get_posts internally).
    • page_limit: Number of pages to fetch.
    • filename: Destination path for the output file. Note: An error is thrown if the file already exists.
    • resume_file: A filename where the link to the next page will be saved. This file is used to resume scraping if interrupted.
    • keys: A list of specific post fields to save (e.g., post_id, text, timestamp). If omitted, all keys are saved.
    • format: Output format, either 'csv' or 'json' (defaults to 'csv').
    • matching / not_matching: Regex patterns to filter posts.
    • days_limit: How far back to fetch posts in days (defaults to 3650).
    import facebook_scraper as fs
    
    # Saves the first 100 pages
    for i in range(1, 101):
        fs.write_posts_to_csv(
            group=GROUP_ID, # The method uses get_posts internally so you can use the same arguments and they will be passed along
            page_limit=100,
            timeout=60,
            options={
                'allow_extra_requests': False
            },
            filename=f'./data/messages_{i}.csv', # Will throw an error if the file already exists
            resume_file='next_page.txt', # Will save a link to the next page in this file after fetching it and use it when starting.
            matching='.+', # A regex can be used to filter all the posts matching a certain pattern (here, we accept anything)
            not_matching='^Warning', # And likewise those that don't fit a pattern (here, we filter out all posts starting with "Warning")
            keys=[
                'post_id',
                'text',
                'timestamp',
                'time',
                'user_id'
            ], # List of the keys that should be saved for each post, will save all keys if not set
            format='csv', # Output file format, can be csv or json, defaults to csv
            days_limit=3650 # Number of days for the oldest post to fetch, defaults to 3650
        )
  4. Extract profile information with get_profile

    master

    The get_profile function extracts information from a profile's 'About' section. You can pass an account name or ID. To access sensitive information like Date of Birth or Gender, you must provide cookies.

    from facebook_scraper import get_profile
    
    # Basic usage
    get_profile("zuck")
    
    # Usage with cookies for more info
    get_profile("zuck", cookies="cookies.txt")
  5. Extract group information with get_group_info

    master

    Use the get_group_info function to retrieve metadata about a Facebook group, such as its ID, name, member count, type, and admins.

    Note: To access the list of admins, you must provide a cookies parameter pointing to a valid cookies file to authenticate your session.

    from facebook_scraper import get_group_info
    get_group_info("makeupartistsgroup") # or get_group_info("makeupartistsgroup", cookies="cookies.txt")
  6. Configure page iteration options

    master

    When using any of the iter_* functions, you can pass additional keyword arguments (**kwargs) to control behavior:

    • start_url: The URL to begin scraping from.
    • request_url_callback: A function called before each new URL request is made.
    • base_url: The base URL used for joining relative links (defaults to FB_MOBILE_BASE_URL).
    • options: A dictionary that can include posts_per_page to adjust the number of posts fetched per request.
  7. Configure post extraction for reactions, reactors, and comments

    master

    When using the scraper, you can pass specific keys in the options dictionary to control the depth of data extraction:

    • reactions: If set, attempts to extract reaction counts.
    • reactors: If set to a number (int/float), limits the number of people reacting to be returned. If set to 'generator', returns a generator instead of a list.
    • sharers: If set, attempts to extract people who shared the post. If set to 'generator', returns a generator instead of a list.
    • comments: If set, attempts to extract full comments. If set to 'generator', returns a generator instead of a list.
    • allow_extra_requests: (Boolean) Controls whether the extractor can make additional requests to fetch high-quality images.
    • HQ_images: (Boolean) Controls whether to attempt fetching high-quality images.
  8. Configure get_posts parameters

    master

    The get_posts function accepts several optional parameters to customize the scraping behavior:

    • group: Group ID to scrape groups instead of pages (Default: None).
    • pages: Number of pages of posts to request. Try a number > 2 as the first two may have no results (Default: 10).
    • timeout: Seconds to wait before timing out (Default: 30).
    • credentials: A tuple of (user, password) to login before requesting posts (Default: None).
    • extra_info: If True, performs an extra request to get post reactions (Default: False).
    • youtube_dl: If True, uses youtube-dl for high-quality video extraction (Default: False).
    • post_urls: A list of URLs or post IDs to extract posts from (alternative to username).
    • cookies: Authentication via:
      • Path to a Netscape or JSON cookie file.
      • A CookieJar object.
      • A dictionary compatible with cookiejar_from_dict.
      • The string "from_browser" to attempt extraction from your browser.
    • options: A dictionary for advanced configuration:
      • "comments": Set to True or an integer to limit the number of comments retrieved.
      • "reactors": Set to True or an integer to limit the number of people reacting.
      • "progress": Set to True to show a tqdm progress bar during comment/reply extraction.
      • "allow_extra_requests": Set to False to disable extra requests (required for full text/image links).
      • "posts_per_page": Number of posts per page (Default: 4).
  9. Fetch share and reaction information for a post

    master

    You can enrich an existing post object (obtained via get_posts) with additional metadata such as reaction counts (LIKE, ANGER, etc.), sharers, and the w3_fb_url. This method may perform additional HTTP requests per post to retrieve the full data.

    Note: This is typically used in conjunction with a post object already retrieved from the scraper.

    # Example: enriching posts with reaction data
    for post in get_posts('fanpage'):
        more_info_post = fetch_share_and_reactions(post)
        print(more_info_post)
  10. Use the facebook-scraper CLI

    master

    You can run the scraper from the command line. Use --help to see all available options. If you encounter UnicodeEncodeError, use the --encoding utf-8 flag.

    $ facebook-scraper --filename nintendo_page_posts.csv --pages 10 nintendo