facebook-scraper
repository·master·Indexed 25 days ago
https://github.com/kevinzg/facebook-scraperA 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.
What's inside facebook-scraper
- You can install the latest release from PyPI using pip, or install the latest master branch directly from GitHub.
Initialize the FacebookScraper client
masterTo use the scraper, instantiate theFacebookScraperclass. You can optionally provide a customsession(usingrequests_html.HTMLSession) orrequests_kwargsfor advanced configuration like proxies or custom headers.Download comments from a specific post
masterTo download comments from a specific post, use
get_postswith thepost_urlsparameter containing thePOST_ID. You must use theoptionsdictionary with thecommentskey 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)Use get_posts to scrape posts
masterThe
get_postsfunction 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])Write posts directly to CSV or JSON with write_posts_to_csv
masterThe
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 (usesget_postsinternally).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 )Extract profile information with get_profile
masterThe
get_profilefunction 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 providecookies.from facebook_scraper import get_profile # Basic usage get_profile("zuck") # Usage with cookies for more info get_profile("zuck", cookies="cookies.txt")Extract group information with get_group_info
masterUse the
get_group_infofunction 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
cookiesparameter 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")Configure page iteration options
masterWhen 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 toFB_MOBILE_BASE_URL).options: A dictionary that can includeposts_per_pageto adjust the number of posts fetched per request.
Configure post extraction for reactions, reactors, and comments
masterWhen using the scraper, you can pass specific keys in the
optionsdictionary 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.
Configure get_posts parameters
masterThe
get_postsfunction 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: IfTrue, performs an extra request to get post reactions (Default:False).youtube_dl: IfTrue, usesyoutube-dlfor 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
CookieJarobject. - 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 toTrueor an integer to limit the number of comments retrieved."reactors": Set toTrueor an integer to limit the number of people reacting."progress": Set toTrueto show atqdmprogress bar during comment/reply extraction."allow_extra_requests": Set toFalseto disable extra requests (required for full text/image links)."posts_per_page": Number of posts per page (Default:4).
Fetch share and reaction information for a post
masterYou can enrich an existing post object (obtained via
get_posts) with additional metadata such as reaction counts (LIKE, ANGER, etc.), sharers, and thew3_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)Use the facebook-scraper CLI
masterYou can run the scraper from the command line. Use
--helpto see all available options. If you encounterUnicodeEncodeError, use the--encoding utf-8flag.$ facebook-scraper --filename nintendo_page_posts.csv --pages 10 nintendo