0
我有這樣的Python代碼通過基於關鍵字Twitter的API獲得的鳴叫,並保存到一個JSON文件:在HTML頁面運行Twitter的API流代碼(蟒蛇)(點擊按鈕)
Python代碼:
import json
import tweepy
from datetime import datetime
from pytz import timezone
import pytz
# put your keys
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_TOKEN_KEY =''
ACCESS_TOKEN_SECRET = ''
# FILTER_KEYWORDS = ['manhattan' + 'nyc']
FILTER_KEYWORDS = ['Twitter']
#FILTER_LANGUAGES = ['en']
#FILTER_LOCATIONS_ALL=[-180,-90,180,90]
#FILTER_LOCATIONS_MANHATTAN=[-74.021248,40.698770 ,-73.905459, 40.872932]
class SimpleTweetStreamer:
def __init__(self):
try:
self.auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
self.auth.set_access_token(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
self.api = tweepy.API(self.auth)
self.sapi = tweepy.streaming.Stream(self.auth, CustomStreamListener(self.api))
self.sapi.filter(track=FILTER_KEYWORDS)
#self.sapi.filter(locations=FILTER_LOCATIONS_MANHATTAN, languages=FILTER_LANGUAGES)
except tweepy.error.TweepError as e:
print("Unable to authenticate", e)
class CustomStreamListener(tweepy.StreamListener):
def __init__(self, api):
self.api = api
def on_data(self, body):
try:
tweet = json.loads(body)
date_format = '%Y-%m-%d'
time_format = '%H:%M:%S'
ts = tweet['timestamp_ms']
date = datetime.fromtimestamp(int(ts)/1000, tz=pytz.timezone('EST'))
tweet['MYT_local_date'] = date.strftime(date_format)
tweet['MYT_local_time'] = date.strftime(time_format)
fileName = 'abc'+ '.json'
with open(fileName, 'a') as outfile:
json.dump(tweet, outfile)
outfile.write("\n")
outfile.flush()
outfile.close()
except:
pass
return True
def on_error(self, status_code):
print("[error] " + str(status_code))
return True # Don't kill the stream
def on_timeout(self):
return True # Don't kill the stream
if __name__ == "__main__":
t = SimpleTweetStreamer()
如何通過單擊HTML頁面中的按鈕來運行此操作?