我的下面的脚本(取自各种在线资源)不是写入数据库。我没有收到任何错误,如果我注释掉数据库行,那么它会毫无问题地输出到控制台。
数据库存在,它有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 '\n %s %s via %s\n' % (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)
答案 0 :(得分:1)
首先,修复你的缩进。你没有得到任何错误,因为你明确地默默了它们!与
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.
答案 1 :(得分:0)
你想这样做:
cur = conn.cursor()
cursor.execute('INSERT INTO tweets (text, date) VALUES (?, NOW())' ,(status.text))
或者这个:
cur = conn.cursor()
cur.execute('INSERT INTO tweets (text, date) VALUES (?, NOW())' ,(status.text))
在第一种情况下cursor
未声明。
此外,正如lqc指出的那样,你可以使所有错误无声。不要抓住任何例外情况来查看正在发生的事情或将其更改为更具体的内容(例如UnicodeError
)。