Scrape hashtags using Twitter API v2 with Tweepy. Handle pagination using next_token, collect tweets until 1000 limit or token exhausted, and respect rate limit headers by sleeping when x-rate-limit-remaining hits 0.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Providing hashtag scraping code with pagination and rate limit handling
The code uses Tweepy Client with the bearer token from environment variables, fetches tweets matching a hashtag using search_recent_tweets, paginates with next_token until 1000 tweets or no more pages, and respects rate limits by sleeping until reset when limit is reached.
Below is a minimal, end‑to‑end example that uses Tweepy’s v2 Client to pull tweets for a given hashtag. It paginates with next_token, stops after 1000 tweets (or when there’s no more data), and respects rate limits by sleeping until reset whenever x-rate-limit-remaining hits 0.
python
import os
import time
import tweepy
def fetch_hashtag_tweets(
hashtag: str,
max_total: int = 1000,
per_request: int = 100
):
"""
Fetch up to `max_total` tweets matching a hashtag, paginating with next_token
and respecting rate limits.
"""
bearer_token = os.environ.get("TWITTER_BEARER_TOKEN")
if not bearer_token:
raise ValueError("TWITTER_BEARER_TOKEN is not set")
client = tweepy.Client(bearer_token=bearer_token)
query = f"#{hashtag} -is:retweet" # example filter to remove retweets
next_token = None
all_tweets = []
while len(all_tweets) < max_total:
resp = client.search_recent_tweets(
query=query,
max_results=per_request,
tweet_fields=[
"id", "text", "created_at", "author_id",
"public_metrics", "lang", "source"
],
expansions=["author_id"],
next_token=next_token
)
# Collect data
if resp.data:
all_tweets.extend(resp.data)
# Check rate limit and wait if needed
if resp.rate_limit:
remaining = resp.rate_limit.remaining
reset_ts = resp.rate_limit.reset # epoch seconds
if remaining == 0:
sleep_for = max(0, reset_ts - time.time())
print(f"Rate limit reached. Sleeping for {sleep_for:.0f} seconds...")
time.sleep(sleep_for)
# Handle pagination
meta = resp.meta or {}
next_token = meta.get("next_token")
# Stop if no more pages or we’ve hit our limit
if not next_token:
break
# Safety check in case we got more than needed in the last batch
if len(all_tweets) >= max_total:
break
# Truncate to the requested max_total, just in case
return all_tweets[:max_total]
if __name__ == "__main__":
hashtag_to_search = "Python" # example
tweets = fetch_hashtag_tweets(hashtag_to_search, max_total=1000, per_request=100)
print(f"Fetched {len(tweets)} tweets for #{hashtag_to_search}.")
for t in tweets[:5]:
print(f"- [{t.id}] {t.text[:100]}...")
How it works:
Set your TWITTER_BEARER_TOKEN in the environment.
search_recent_tweets returns a Tweepy Response object:
resp.data holds the tweet objects.
resp.meta contains pagination info (e.g., next_token).
resp.rate_limit (if present) has .remaining, .reset, etc., derived from the x-rate-limit-* headers.
The loop continues until 1000 tweets are collected or no next_token is returned.
If resp.rate_limit.remaining hits 0, the code sleeps until the reset time.