Datasets:
File size: 4,726 Bytes
8817cc6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
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() |