我正在尝试抓取从2012年1月1日到2018年12月31日7年的数据。我正在使用 tweepy,我有以下代码
usernames = ["CNBC","MarketWatch","verge","YahooFinance"]
api = tweepy.API(auth)
start_date = datetime.datetime(2012,1,1,0,0,0)
end_date = datetime.datetime(2017,12,31,0,0,0)
def create_dictionary(username="",tweet_id="",time="",text="",retweet_count=0,favourite_count=0):
return {
"USERNAME": username,
"TWEET_ID": tweet_id,
"TIME": time,
"TWEET": text,
"RETWEET_COUNT":retweet_count,
"FAVOURITE_COUNT":favourite_count
}
tweet_id = []
time = []
tweet = []
rt_count = []
fav_count = []
for i,username in enumerate(usernames):
print("Scraping for {}".format(username))
for status in tweepy.Cursor(api.user_timeline,id=username).items():
print(f'Last status had timestamp @ {status.created_at}')
if status.created_at < start_date:
break
if (status.created_at >= start_date and status.created_at <= end_date) :
tweet_id.append(str(status.id))
time.append(str(status.created_at))
tweet.append(status.text)
rt_count.append(status.retweet_count)
fav_count.append(status.favorite_count)
dictionary = [
create_dictionary(username=username,
tweet_id = val[0],time=val[1],text=val[2],retweet_count=val[3],favourite_count=val[4])
for val in zip(tweet_id,time,tweet,rt_count,fav_count)
]
clear_output(wait=True)
try:
print("Going for the next username {}".format(usernames[i+1]))
except:
print("Done")
pass
with open('training_tweets.json', 'a') as fp:
json.dump(dictionary, fp,indent=4)
没有任何内容被抓取,它会移动到下一个用户名,
[]
正在转储到 json 文件中。
是否有速率限制,是否有其他 API 可以抓取历史 Twitter 数据?
您在这里使用的方法是点击 Twitter 用户时间线端点。此 API 仅支持检索单个用户最多 3200 条最新推文。
您列出的所有帐户都是大容量媒体帐户,迄今为止发布了数十万条推文,因此您在结果集中看到 2017 年的任何推文的可能性非常小。
为了检索该时间段内的推文,您需要使用 Twitter 的完整存档搜索 API,这是一个具有有限免费套餐的高级 API。成交量可能会很高。