| import praw |
| import pandas as pd |
| from datetime import datetime, timezone |
| from textblob import TextBlob |
| import csv |
| import time |
|
|
| |
| client_id = '' |
| client_secret = '' |
| user_agent = '' |
|
|
| |
| reddit = praw.Reddit( |
| client_id=client_id, |
| client_secret=client_secret, |
| user_agent=user_agent |
| ) |
|
|
| |
| subreddits = ["climate", "energy","renewableenergy","climatechange"] |
|
|
| |
| data = [] |
|
|
| |
| def process_request(): |
| retry_count = 0 |
| max_retries = 5 |
|
|
| while retry_count < max_retries: |
| try: |
| |
| for subreddit_name in subreddits: |
| |
| subreddit = reddit.subreddit(subreddit_name) |
|
|
| |
| top_posts = subreddit.top(limit=10000) |
| count = 0 |
| |
| for post in top_posts: |
| count += 1 |
| print(count) |
| |
| post_title = post.title |
| |
| for comment in post.comments[:20]: |
| |
| comment_body = comment.body |
| |
| upvotes = comment.score |
| data_dict = { |
| "ID": comment.id, |
| "Author": comment.author.name if comment.author else 'N/A', |
| "Subreddit": subreddit_name, |
| "Post Title": post_title, |
| "Comment Body": comment_body, |
| "Timestamp": datetime.utcfromtimestamp(comment.created_utc), |
| "Upvotes": upvotes, |
| "Number of Replies": len(list(comment.replies)) |
| } |
| data.append(data_dict) |
| print(data_dict) |
| except praw.exceptions.RedditAPIException as e: |
| if 'ratelimit' in str(e).lower(): |
| |
| retry_count += 1 |
| wait_time = 2 ** retry_count |
| print(f"Rate limit exceeded. Waiting {wait_time} seconds and retrying...") |
| time.sleep(wait_time) |
| else: |
| |
| print(f"Error: {e}") |
| |
| retry_count += 1 |
| wait_time = 2 ** retry_count |
| print(f"Rate limit exceeded. Waiting {wait_time} seconds and retrying...") |
| time.sleep(wait_time) |
| else: |
| |
| break |
| else: |
| |
| print("Max retries reached. Consider adjusting your backoff strategy or rate limits.") |
| process_request() |
| |
| |
| with open('', mode='w', newline='', encoding='utf-8') as csv_file: |
| fieldnames = ["ID","Author","Subreddit", "Post Title", "Comment Body", |
| "Timestamp","Upvotes","Number of Replies"] |
| writer = csv.DictWriter(csv_file, fieldnames=fieldnames) |
| writer.writeheader() |
| for d in data: |
| writer.writerow(d) |