【问题标题】:Python tweepy writing to sqlite3 dbPython tweepy 写入 sqlite3 db
【发布时间】:2012-07-12 00:14:53
【问题描述】:

我下面的脚本(取自各种在线资源)没有写入数据库。我没有收到任何错误,如果我注释掉数据库行,那么它会毫无问题地输出到控制台。

数据库存在,它有 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)

【问题讨论】:

  • 如果 cur 确实在您的 try 块内,那么您可能希望传递给 cursor.execute('...', (status.text,)) - 请注意尾随逗号使其成为 1 元组。
  • 您需要缩进 on_status 块(它目前不是 StreamListener 类的一部分,并且永远不会在您的代码中调用)。
  • 谢谢。顶部的修订脚本 - 现在出现错误 406。在我退出之前有什么想法吗?谢谢。

标签: python tweepy


【解决方案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.

【讨论】:

    【解决方案2】:

    你想这样做吗:

    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)。

    【讨论】:

    • 感谢您的回复 - 更新了代码。没有错误,但记录未能出现在 db 中。
    • cur.execute('INSERT INTO tweets (text, date) VALUES (?, ?)' ,(status.text,)) 您输入了一个值,但您有两个“?”。尝试插入一些常量,看看它是否有效,我们会知道这是评论问题还是 tweepy 问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 2011-11-27
    相关资源
    最近更新 更多