本文介绍了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.
这篇关于Python tweepy写入到sqlite3 db的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!