Grok 4.1 Fast· xai
Frontier Reasoning Traces
Implement a Python script to scrape and store Reddit data.
- User
Implement a Python script to scrape and store Reddit data.
- Assistant
Implement a Python script to scrape and store Reddit data.
#!/usr/bin/env python3
"""
Reddit Data Fetcher and Storage Script
======================================
This script uses the official Reddit API via PRAW (Python Reddit API Wrapper)
to fetch posts from a specified subreddit and store them in a JSON file.
This is the recommended and TOS-compliant way to access Reddit data.
Requirements:
- Python 3.6+
- Install PRAW: `pip install praw`
Setup Instructions:
1. Create a Reddit app at https://www.reddit.com/prefs/apps
- Choose "script" type
- Note your client_id (under the app name), client_secret, and set a user_agent (e.g., "MyRedditScraper/1.0")
2. Replace the placeholders below with your credentials.
Usage:
python reddit_scraper.py
Configuration:
Edit the CONFIG dict below.
"""
import praw
import json
from datetime import datetime
from typing import Dict, List
# Configuration
CONFIG = {
"client_id": "YOUR_CLIENT_ID_HERE",
"client_secret": "YOUR_CLIENT_SECRET_HERE",
"user_agent": "RedditDataFetcher/1.0 (by u/yourusername)",
"subreddit": "python", # Change to desired subreddit
"limit": 100, # Number of posts to fetch (respects Reddit rate limits)
"sort": "hot", # 'hot', 'top', 'new', 'controversial', 'rising'
"time_filter": "day", # For 'top'/'controversial': 'hour', 'day', 'week', 'month', 'year', 'all'
"output_file": f"reddit_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
}
def fetch_reddit_data(config: Dict) -> List[Dict]:
"""
Fetch posts from Reddit using PRAW.
"""
reddit = praw.Reddit(
client_id=config["client_id"],
client_secret=config["client_secret"],
user_agent=config["user_agent"],
)
subreddit = reddit.subreddit(config["subreddit"])
posts = []
post_fetcher = getattr(subreddit, config["sort"])
# Handle time_filter for top/controversial
kwargs = {"limit": config["limit"]}
if config["sort"] in ["top", "controversial"]:
kwargs["time_filter"] = config["time_filter"]
for submission in post_fetcher(**kwargs):
post_data = {
"id": submission.id,
"title": submission.title,
"score": submission.score,
"num_comments": submission.num_comments,
"url": submission.url,
"permalink": submission.permalink,
"author": submission.author.name if submission.author else "[deleted]",
"created_utc": submission.created_utc,
"is_self": submission.is_self,
"selftext": submission.selftext[:500] + "..." if submission.selftext and len(submission.selftext) > 500 else submission.selftext, # Truncate long text
"flair_text": submission.link_flair_text,
"upvote_ratio": submission.upvote_ratio,
"over_18": submission.over_18,
}
posts.append(post_data)
return posts
def save_to_json(data: List[Dict], filename: str):
"""
Save data to a JSON file.
"""
with open(filename, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False, default=str)
print(f"Data saved to {filename} ({len(data)} posts)")
def main():
if CONFIG["client_id"] == "YOUR_CLIENT_ID_HERE":
print("Error: Please configure your Reddit API credentials in the CONFIG dict.")
return
print(f"Fetching {CONFIG['limit']} {CONFIG['sort']} posts from r/{CONFIG['subreddit']}...")
try:
posts = fetch_reddit_data(CONFIG)
save_to_json(posts, CONFIG["output_file"])
print("Done!")
except Exception as e:
print(f"Error: {e}")
print("Check your credentials, rate limits, or subreddit name.")
if __name__ == "__main__":
main()
submission.comments loop.fetch_reddit_data() (e.g., for comment in submission.comments[:10]:).Run it after setup! 🚀