如何使用tweepy提取两个日期之间的推文?

时间:2019-09-12 20:41:22

标签: python twitter tweepy

我有一个代码,用于使用开发者帐户根据位置和关键字提取推文。我可以实时接收推文,但我希望提取两个日期之间的推文。我读过的文章说,我们可以追溯到历史上的最大距离是今天的2周。因此,我正在使用下面的代码,但它似乎不起作用。

#Twitter API credentials
consumer_key = '#####'
consumer_secret = '######'
access_token = '#####'
access_token_secret = '#######'
startDate = datetime.datetime(2019, 6, 1, 0, 0, 0)
endDate =   datetime.datetime(2019, 9, 1, 0, 0, 0)

file_exists = os.path.isfile('searchtweets.csv')

with io.open('searchtweets2.csv', 'w', newline='', encoding='utf-8') as csvfile:
        fieldnames = ['Text', 'Username', 'User', 'User_location', 'User_coordinates']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        if not file_exists:
                writer.writeheader()


class listener(StreamListener):
        def on_data(self, data):
                all_data = json.loads(data)

                # collect all desired data fields
                if 'text' in all_data:
                        tweet          = str(all_data["text"]).encode("utf-8", errors='ignore')
                        username       = str(all_data["user"]["screen_name"]).encode("utf-8", errors='ignore')
                        user           = str(all_data["user"]["id"]).encode("utf-8", errors='ignore')
                        user_location  = str(all_data["user"]["location"]).encode("utf-8", errors='ignore')
                        user_coordinates   = str(all_data["coordinates"]).encode("utf-8", errors='ignore')
                        #print(str(all_data).encode("utf-8", errors='ignore'))
                        print(tweet)
                        with io.open('searchtweets2.csv', 'a', newline='', encoding='utf-8') as csvfile:
                                fieldnames = ['Text', 'Username', 'User', 'User_location', 'User_coordinates']
                                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
 #                               if "alaska".encode("utf-8", errors='ignore') in user_location:
                                writer.writerow({'Text': tweet, 'User': user, 'Username': username,
                                                 'User_location': user_location, 'User_coordinates': user_coordinates})

                        return(True)
                def on_error(self, status):
                        print (status)

auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)


twitterStream = Stream(auth, listener())
twitterStream.filter(track=["flowers","choclate"],languages = ["en"], locations = "-122,36,-121,37", since=startDate, until=endDate ,
                     stall_warnings = True)  

当我运行上面的代码时,我收到错误消息,提示意外的键参数“自”。 我是python的新手,请帮助我将参数放在代码中的正确位置以使其运行。

谢谢。

0 个答案:

没有答案