我会使用搜索 API。我用下面的代码做了类似的事情。它似乎完全按预期工作。我在一个特定的电影明星身上使用了它,并拉出了 15568 条推文,在快速扫描后,所有这些似乎都是@提及它们。 (我从他们的整个时间线中提取出来。)
在您的情况下,在您希望每天运行的搜索中,我会存储您为每个用户提取的最后一次提及的 id,并在每次重新运行时将该值设置为“sinceId”搜索。
顺便说一句,AppAuthHandler 比 OAuthHandler 快得多,而且此类数据拉取不需要用户身份验证。
auth = tweepy.AppAuthHandler(consumer_token, consumer_secret)
auth.secure = True
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
searchQuery = '@username' 这就是我们要搜索的内容。在您的情况下,我将创建一个列表并遍历搜索查询运行的每次传递中的所有用户名。
retweet_filter='-filter:retweets' 这会过滤掉转发
在下面的每个 api.search 调用中,我会将以下内容作为查询参数放入:
q=searchQuery+retweet_filter
以下代码(以及上面的 api 设置)来自this link:
tweetsPerQry = 100 # 这是 API 允许的最大值
fName = 'tweets.txt' # 我们会将推文存储在一个文本文件中。
如果需要从特定 ID 开始的结果,请将 sinceId 设置为该 ID。
否则默认无下限,只要 API 允许就回溯
sinceId = None
如果结果仅低于特定 ID,请将 max_id 设置为该 ID。
否则默认无上限,从匹配搜索查询的最新推文开始。
max_id = -1L
//however many you want to limit your collection to. how much storage space do you have?
maxTweets = 10000000
tweetCount = 0
print("Downloading max {0} tweets".format(maxTweets))
with open(fName, 'w') as f:
while tweetCount < maxTweets:
try:
if (max_id <= 0):
if (not sinceId):
new_tweets = api.search(q=searchQuery, count=tweetsPerQry)
else:
new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
since_id=sinceId)
else:
if (not sinceId):
new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
max_id=str(max_id - 1))
else:
new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
max_id=str(max_id - 1),
since_id=sinceId)
if not new_tweets:
print("No more tweets found")
break
for tweet in new_tweets:
f.write(jsonpickle.encode(tweet._json, unpicklable=False) +
'\n')
tweetCount += len(new_tweets)
print("Downloaded {0} tweets".format(tweetCount))
max_id = new_tweets[-1].id
except tweepy.TweepError as e:
# Just exit if any error
print("some error : " + str(e))
break
print ("Downloaded {0} tweets, Saved to {1}".format(tweetCount, fName))