Python tweepy写入到sqlite3 db
问题描述
我下面的脚本(摘自各种在线资源)没有写入数据库。我没有收到任何错误,如果我注释掉数据库行,则它会毫无问题地输出到控制台。数据库存在,它有2个字段,可由我写入...有什么想法吗?
已更新以下代码
#!/usr/bin/env python
import sys
import tweepy
from textwrap import TextWrapper
import sqlite3
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_KEY = ''
ACCESS_SECRET = ''
auth1 = tweepy.auth.OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
auth1.set_access_token(ACCESS_KEY,ACCESS_SECRET)
api = tweepy.API(auth1)
conn = sqlite3.connect('twitter.db')
cur = conn.cursor()
class StreamListener(tweepy.StreamListener):
status_wrapper = TextWrapper(width=60, initial_indent=' ', subsequent_indent=' ')
def on_status(self, status):
try:
cur.execute('INSERT INTO tweets (text, date) VALUES (?, ?)' ,(status.text,))
print self.status_wrapper.fill(status.text)
print '
%s %s via %s
' % (status.author.screen_name, status.created_at, status.source)
conn.commit()
except Exception, e:
print >> sys.stderr, 'Encountered Exception:', e
def on_error(self, status_code):
print >> sys.stderr, 'Encountered error with status code:', status_code
return True # Don't kill the stream
def on_timeout(self):
print >> sys.stderr, 'Timeout...'
return True # Don't kill the stream
streamer = tweepy.Stream(auth1, StreamListener(), timeout=None)
setTerms = ['news','hello']
streamer.filter(setTerms)
解决方案
首先,修复缩进。您不会收到任何错误,因为您显式地让它们静默了!使用
except Exception, e:
# Catch any unicode errors while printing to console
# and just ignore them to avoid breaking application.
pass
这将捕获try: except:
块中发生的任何异常。阅读Python教程是一项good start to learn more about exceptions.
相关文章