簡體   English   中英

Python tweepy寫入sqlite3 db

[英]Python tweepy writing to 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 '\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)

首先,修復縮進。 您沒有得到任何錯誤,因為您正在明確消除它們!

except Exception, e:
    # Catch any unicode errors while printing to console
    # and just ignore them to avoid breaking application.
    pass

這捕獲了try: except:塊中發生的任何異常。 閱讀Python教程是學習更多有關異常好開始。

您要這樣做嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM