reddit_climate_comment / reddit_collect_data.py
cathw's picture
Upload reddit_collect_data.py
8817cc6 verified
import praw
import pandas as pd
from datetime import datetime, timezone
from textblob import TextBlob
import csv
import time
# Replace these with your own values
client_id = ''
client_secret = ''
user_agent = ''
# Create a Reddit instance
reddit = praw.Reddit(
client_id=client_id,
client_secret=client_secret,
user_agent=user_agent
)
# Create a list of subreddits to collect data from
subreddits = ["climate", "energy","renewableenergy","climatechange","climateactionplan","environment","sustainability","zerowaste"]
data = []
# Example of an enhanced backoff strategy
def process_request():
retry_count = 0
max_retries = 5 # You can adjust this based on your needs
while retry_count < max_retries:
try:
# Iterate over each subreddit in the subreddits list
for subreddit_name in subreddits:
# Choose the subreddit you want to interact with
subreddit = reddit.subreddit(subreddit_name)
# Get the top 100 posts in the subreddit
top_posts = subreddit.top(limit=1000)
count = 0
# Iterate over each post in the top_posts list
for post in top_posts:
count += 1
print(count)
# Get the title of the post
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]:
# Get the body of the comment
comment_body = comment.body
# Get the number of upvotes for the comment
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():
# If a rate limit error is encountered, wait and then retry
retry_count += 1
wait_time = 2 ** retry_count # Exponential backoff
print(f"Rate limit exceeded. Waiting {wait_time} seconds and retrying...")
time.sleep(wait_time)
else:
# Handle other API exceptions if needed
print(f"Error: {e}")
# If a rate limit error is encountered, wait and then retry
retry_count += 1
wait_time = 2 ** retry_count # Exponential backoff
print(f"Rate limit exceeded. Waiting {wait_time} seconds and retrying...")
time.sleep(wait_time)
else:
# If the request was successful, break out of the loop
break
else:
# If max_retries is reached, consider logging an error or taking appropriate action
print("Max retries reached. Consider adjusting your backoff strategy or rate limits.")
process_request()