【问题标题】:Tweepy exception when storing trends in a database not when printing them将趋势存储在数据库中而不是打印趋势时出现 Tweepy 异常
【发布时间】:2018-03-10 09:33:02
【问题描述】:

我正在使用 Python 3.6.2 和 Tweepy 3.3.0。

因此,当我尝试通过 Tweepy API 从 Twitter 检索趋势并在我的控制台中打印它们时,它工作得非常好,如下所示:

auth = tweepy.OAuthHandler(cons_tok, cons_sec)
auth.set_access_token(app_tok, app_sec)
twitter_api = tweepy.API(auth)

trends = twitter_api.trends_place(1)

for trend in trends[0]["trends"]:
    print(trend['name'])

它工作正常,我有一个清单。

现在,当我尝试将这些存储到数据库中时(我选择 SQLite 只是为了尝试):

class TwitterMain():
    def __init__(self, conn):
        self.auth = tweepy.OAuthHandler(cons_tok, cons_sec)
        self.auth.set_access_token(app_tok, app_sec)

        self.api = tweepy.API(self.auth)
        self.conn = conn
        self.c = self.conn.cursor()

    def get_trends(self):
        trends = self.api.trends_place(1)
        trend_data = []

        for trend in trends[0]["trends"]:
            trend_tweets = []
            trend_tweets.append(trend['name'])
            tt = tweepy.Cursor(self.api.search, q = trend['name']).items(3)

            for t in tt:                
                trend_tweets.append(self.get_tweet_html(t.id))

            trend_data.append(tuple(trend_tweets))

        self.c.executemany("INSERT INTO trend_data VALUES (?,?,?,?, DATETIME('now'))", trend_data)
        self.conn.commit()

    def get_tweet_html(self, id):
        oembed = self.api.get_oembed(id=id, hide_media = True, hide_thread = True)

        tweet_html = oembed['html'].strip("\n")

        return tweet_html


if __name__ == "__main__":

    try:
        conn = sqlite3.connect(db)        
        twit = TwitterMain(conn)
        twit.get_trends()

    except Exception as e:
        print(e.__doc__)

    finally:
        conn.close()

这只是我存储趋势数据的部分。数据库和表已经创建。

运行它会创建一个 Tweepy 异常,并且在在线搜索时它说这是时间限制,但如果是这样,为什么当我只是打印时它工作正常而不是当我尝试存储它们时?

【问题讨论】:

    标签: python-3.x twitter tweepy


    【解决方案1】:

    没有可以插入值的表,并且您提供的代码正在引发异常:

    self.c.executemany("INSERT INTO trend_data VALUES (?,?,?,?, DATETIME('now'))", trend_data)
    sqlite3.OperationalError: no such table: trend_data
    

    只需在 init 方法中添加一行来创建表:

    self.c.execute("""CREATE TABLE mytable
                     (c1,c2,c3,c4,c5)""")
    

    并使用它来填写值:

    self.c.executemany("INSERT INTO mytable VALUES (?,?,?,?, DATETIME('now'))", trend_data)
    

    【讨论】:

    • 在我的问题中,我的字面意思是:“这只是我存储趋势数据的部分。”这意味着为了重新创建整个场景,您只需要创建一个表并进行导入,显然我做到了。
    • 请参阅 SO 政策关于最小、完整和可验证示例。 stackoverflow.com/help/mcve 。我无法猜到你写的是故意的,而不是程序员的错误!
    • 再次:我说:这只是我存储趋势数据的部分。 数据库和表已经创建。所以我说我已经创建了表格,你告诉我你的错误是你必须创建一个表格
    猜你喜欢
    • 2021-01-13
    • 2020-02-05
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 2021-07-15
    • 1970-01-01
    • 2011-08-09
    相关资源
    最近更新 更多