【发布时间】: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