|
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","climateactionplan","environment","sustainability","zerowaste"] |
|
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=1000) |
|
count = 0 |
|
|
|
for post in top_posts: |
|
count += 1 |
|
print(count) |
|
|
|
post_id = post.id |
|
if hasattr(post, 'post_hint') and post.post_hint == 'image': |
|
image_url = post.url |
|
else: |
|
image_url = "" |
|
for comment in post.comments[:len(list(post.comments))-1]: |
|
|
|
comment_body = comment.body |
|
|
|
upvotes = comment.score |
|
for reply in comment.replies[:len(list(comment.replies))-1]: |
|
data_dict = { |
|
"Subreddit": subreddit_name, |
|
"Post Title": post.title, |
|
"Post ID": post.id, |
|
"Post Author": post.author, |
|
"Post Body": post.selftext, |
|
"Post Url": post.url, |
|
"Post Pic": image_url, |
|
"Post Timestamp": datetime.utcfromtimestamp(post.created_utc), |
|
"Post Upvotes": post.score, |
|
"Post Permalink": post.permalink, |
|
"Comment ID": comment.id, |
|
"Comment Author": comment.author.name if comment.author else 'N/A', |
|
"Comment Body": comment_body, |
|
"Comment Timestamp": datetime.utcfromtimestamp(comment.created_utc), |
|
"Comment Upvotes": upvotes, |
|
"Comment Permalink": comment.permalink, |
|
"Reply ID": reply.id, |
|
"Reply Author": reply.author, |
|
"Reply Body": reply.body, |
|
"Reply Timestamp": datetime.utcfromtimestamp(reply.created_utc), |
|
"Reply Upvotes": reply.score, |
|
"Reply Permalink": reply.permalink |
|
} |
|
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() |