我使用Tweepy Library使用Python代码检索特定主题标签的Twitter数据,但问题是我需要检索特定的时间段,例如,2013年6月30日至2013年12月30日。我怎么能那样做?
#imports
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
#setting up the keys
consumer_key = '……………….'
consumer_secret = '……………..'
access_token = '……………….'
access_secret = '……………..'
class TweetListener(StreamListener):
# A listener handles tweets are the received from the stream.
#This is a basic listener that just prints received tweets to standard output
def on_data(self, data):
print (data)
return True
def on_error(self, status):
print (status)
#printing all the tweets to the standard output
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
stream = Stream(auth, TweetListener())
t = u"#سوريا"
stream.filter(track=[t])
答案 0 :(得分:3)
我仍在调查为什么我无法使用tweepy.Cursor(api.search, geocode=.., q=query, until=date )
获得相同的结果。也许这是reason。但我可以在两个日期之间使用Tweepy检索Twitter数据,并通过这些步骤。
首先,我在开始日期和结束日期之间创建了日期生成器。
def date_range(start,end):
current = start
while (end - current).days >= 0:
yield current
current = current + datetime.timedelta(seconds=1) #Based on your need, but you could do it per day/minute/hour
然后,我创建了一个Listener
,这样我就可以通过访问status.created_at
来获取在特定日期创建的推文
您的代码应如下所示:
import tweepy
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json
import datetime
#Use your keys
consumer_key = '...'
consumer_secret = '...'
access_token = '...'
access_secret = '...'
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
def date_range(start,end):
current = start
while (end - current).days >= 0:
yield current
current = current + datetime.timedelta(seconds=1)
class TweetListener(StreamListener):
def on_status(self, status):
#api = tweepy.API(auth_handler=auth)
#status.created_at += timedelta(hours=900)
startDate = datetime.datetime(2013, 06, 30)
stopDate = datetime.datetime(2013, 10, 30)
for date in date_range(startDate,stopDate):
status.created_at = date
print "tweet " + str(status.created_at) +"\n"
print status.text + "\n"
# You can dump your tweets into Json File, or load it to your database
stream = Stream(auth, TweetListener(), secure=True, )
t = u"#Syria" # You can use different hashtags
stream.filter(track=[t])
输出:
我刚刚打印了要检查的日期(我不想用政治推文垃圾邮件StackOverflow)。
tweet 2013-06-30 00:00:01
-------------------
tweet 2013-06-30 00:00:02
-------------------
tweet 2013-06-30 00:00:03
-------------------
tweet 2013-06-30 00:00:04
-------------------
tweet 2013-06-30 00:00:05
-------------------
tweet 2013-06-30 00:00:06
-------------------
tweet 2013-06-30 00:00:07
-------------------
tweet 2013-06-30 00:00:08
-------------------
tweet 2013-06-30 00:00:09
-------------------