我想将Python shell数据存储到数据库中

时间:2015-09-07 05:30:42

标签: python tweepy

我是Python新手。我使用此代码来获取用户的详细信息(目前在Python shell中)。

import tweepy
import time
import sqlite3
import os
from datetime import datetime
auth = tweepy.OAuthHandler(key,secret)
auth.set_access_token(access_token, access_secter)
api = tweepy.API(auth)
user = api.get_user('<the_user_to_query_on_here>')
print ("User id: " + user.id_str)
print ("Screen_Name: " + user.screen_name)
print (user.name)
print ("Description: " + user.description)
print ("Language: " + user.lang)
print ("Account created at: " + str(user.created_at))
print ("Location: " + user.location)
print ("Time zone: " + user.time_zone)
print ("Number of tweets: " + str(user.statuses_count))
print ("Number of followers: " + str(user.followers_count))
print ("Number of Following: " + str(user.friends_count))
print ("A member of " + str(user.listed_count) + " lists.")
print ("Retreiving friends for", user.screen_name)
for friend in user.friends():
    print ("Following_Names: " + str(friend.screen_name))

我想将此信息存储在数据库中,以便以后可以在本地检索它。我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用已包含在Python中的SQLite3作为可能的解决方案。

您需要做什么,而不是为每个人调用print(),将其分配给变量,然后将该变量存储到数据库中。

例如,更改:

print ("User id: " + user.id_str)
print ("Screen_Name: " + user.screen_name)

user_id = user.id_str
screen_same = user.screen_name

然后打开与数据库的连接(只要它不连续循环之前或之后)并使用以下方法存储这些变量:

import sqlite3 as lite
import sys

con = lite.connect('twitter.db')

with con:

    cur = con.cursor()
    # the following line only needed once to create the table
    cur.execute("CREATE TABLE Twitter(User ID, Screen Name, etc...)") 
    cur.execute("INSERT INTO Twitter VALUES(user_id,screen_name, etc...)")
    # or
    # you can insert user.id_str directly without assigning it to a variable
    # cur.execute("INSERT INTO Twitter VALUES(user.id_str,user.screen_name, etc...)")

这是关于SQLite3的一个很棒的tutorial