使用Twitter Stream API與Python進行大面積推文收集的最佳方式是什麼?如何使用Tweepy執行全國範圍的Twitter流搜索?
我對地理位置感興趣,尤其是北美地區的全國範圍內的推文收藏。我目前正在使用Python和Tweepy從推特流媒體API轉儲推文到MongoDB數據庫。
我目前正在使用API的位置過濾器在邊界框內拉動推文,然後我進一步過濾爲僅存儲帶有座標的推文。我發現,如果我的邊界框足夠大,我碰上一個Python連接錯誤:
raise ProtocolError('Connection broken: %r' % e, e)
requests.packages.urllib3.exceptions.ProtocolError: ('Connection broken: IncompleteRead(0 bytes read)', IncompleteRead(0 bytes read))
我所做的邊界盒小(我已經成功嘗試NYC紐約和+新英格蘭),但它看起來像錯誤返回一個足夠大的邊界框。我也嘗試了同時運行多個StreamListeners的意圖,但我不認爲這個API允許這個(我得到了420個錯誤),或者至少不是我嘗試的方式。
我使用Tweepy建立一個自定義StreamListener
類:
class MyListener(StreamListener):
"""Custom StreamListener for streaming data."""
# def __init__(self):
def on_data(self, data):
try:
db = pymongo.MongoClient(config.db_uri).twitter
col = db.tweets
decoded_json = json.loads(data)
geo = str(decoded_json['coordinates'])
user = decoded_json['user']['screen_name']
if geo != "None":
col.insert(decoded_json)
print("Geolocated tweet saved from user %s" % user)
else: print("No geo data from user %s" % user)
return True
except BaseException as e:
print("Error on_data: %s" % str(e))
time.sleep(5)
return True
def on_error(self, status):
print(status)
return True
這是我Thread
類的樣子:
class myThread(threading.Thread):
def __init__(self, threadID, name, streamFilter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.streamFilter = streamFilter
def run(self):
print("Starting " + self.name)
#twitter_stream.filter(locations=self.streamFilter)
Stream(auth, MyListener()).filter(locations=self.streamFilter)
而且main
:
if __name__ == '__main__':
auth = OAuthHandler(config.consumer_key, config.consumer_secret)
auth.set_access_token(config.access_token, config.access_secret)
api = tweepy.API(auth)
twitter_stream = Stream(auth, MyListener())
# Bounding boxes:
northeast = [-78.44,40.88,-66.97,47.64]
texas = [-107.31,25.68,-93.25,36.7]
california = [-124.63,32.44,-113.47,42.2]
northeastThread = myThread(1,"ne-thread", northeast)
texasThread = myThread(2,"texas-thread", texas)
caliThread = myThread(3,"cali-thread", california)
northeastThread.start()
time.sleep(5)
texasThread.start()
time.sleep(10)
caliThread.start()