Tweepy to sqlite3

亡梦爱人 提交于 2021-02-17 06:59:07

问题


I'm trying to use Twitter's Streaming API to save tweets to a database using sqlite3. The problem is my database comes back empty. I'm using DB Browser for SQLIte to check the schema and the table and columns are there but no values for any column. Any thoughts?

#create sql table
conn = sqlite3.connect('twitter_one5.db')
c = conn.cursor()
c.execute('''CREATE TABLE tweets
    (coordinates integer,
    place text)''')
conn.commit()
conn.close()

# open connection
conn = sqlite3.connect('twitter_one5.db')
c = conn.cursor()

Create a class to handle inserting tweet info into database:

class Tweet():

    # data from tweet
    def __init__(self, coordinates, place):
        self.coordinates = coordinates
        self.place = place

    # insert data from tweet into DB
    def insertTweet(self):
        c.execute("INSERT INTO tweets (coordinates, place) VALUES(?, ?)", 
        (self.coordinates, self.place))
        conn.commit()

Create a tweet listener using the Streaming API:

class listener(tweepy.StreamListener):

    def on_status(self, status):

        tweet_data  = Tweet(status.coordinates, status.place)
        tweet_data.insertTweet()
        print('inserted')

Create instance of listener and filter for keywords:

l = listener()
stream = tweepy.Stream(auth, l)
stream.filter(track=['twitter'])

来源:https://stackoverflow.com/questions/43750209/tweepy-to-sqlite3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!