2013-03-26 23 views
10

Sto tentando di recuperare i dati da Twitter, utilizzando Tweepy per un nome utente digitato sulla riga di comando. Sto cercando di estrarre un bel po 'di dati sullo stato e sull'utente, quindi ho trovato il seguente:Come posso recuperare tutti i Tweet e gli attributi per un dato utente usando Python?

Nota che sto importando tutti i moduli richiesti ok e ho i tasti oauth + (solo non incluso qui) e il nome del file è corretto, basta stati cambiati:

# define user to get tweets for. accepts input from user 
user = tweepy.api.get_user(input("Please enter the twitter username: ")) 

# Display basic details for twitter user name 
print (" ") 
print ("Basic information for", user.name) 
print ("Screen Name:", user.screen_name) 
print ("Name: ", user.name) 
print ("Twitter Unique ID: ", user.id) 
print ("Account created at: ", user.created_at) 

timeline = api.user_timeline(screen_name=user, include_rts=True, count=100) 
    for tweet in timeline: 
     print ("ID:", tweet.id) 
     print ("User ID:", tweet.user.id) 
     print ("Text:", tweet.text) 
     print ("Created:", tweet.created_at) 
     print ("Geo:", tweet.geo) 
     print ("Contributors:", tweet.contributors) 
     print ("Coordinates:", tweet.coordinates) 
     print ("Favorited:", tweet.favorited) 
     print ("In reply to screen name:", tweet.in_reply_to_screen_name) 
     print ("In reply to status ID:", tweet.in_reply_to_status_id) 
     print ("In reply to status ID str:", tweet.in_reply_to_status_id_str) 
     print ("In reply to user ID:", tweet.in_reply_to_user_id) 
     print ("In reply to user ID str:", tweet.in_reply_to_user_id_str) 
     print ("Place:", tweet.place) 
     print ("Retweeted:", tweet.retweeted) 
     print ("Retweet count:", tweet.retweet_count) 
     print ("Source:", tweet.source) 
     print ("Truncated:", tweet.truncated) 

Vorrei che questo alla fine a scorrere tutti i tweet di un utente (fino al limite di 3200). Per prima cosa, però. Finora se ho due problemi, ottengo il seguente messaggio di errore relativo retweet:

Please enter the twitter username: barackobamaTraceback (most recent call last): 
    File " usertimeline.py", line 64, in <module> 
    timeline = api.user_timeline(screen_name=user, count=100, page=1) 
    File "C:\Python32\lib\site-packages\tweepy-1.4-py3.2.egg\tweepy\binder.py", line 153, in _call 
    raise TweepError(error_msg) 
tweepy.error.TweepError: Twitter error response: status code = 401 
Traceback (most recent call last): 
    File "usertimeline.py", line 42, in <module> 
    user = tweepy.api.get_user(input("Please enter the twitter username: ")) 
    File "C:\Python32\lib\site-packages\tweepy-1.4-py3.2.egg\tweepy\binder.py", line 153, in _call 
    raise TweepError(error_msg) 
tweepy.error.TweepError: Twitter error response: status code = 404 

Passando il nome utente come variabile sembra essere un problema anche:

Traceback (most recent call last): 
    File " usertimleline.py", line 64, in <module> 
    timeline = api.user_timeline(screen_name=user, count=100, page=1) 
    File "C:\Python32\lib\site-packages\tweepy-1.4-py3.2.egg\tweepy\binder.py", line 153, in _call 
    raise TweepError(error_msg) 
tweepy.error.TweepError: Twitter error response: status code = 401 

Ho isolato entrambe queste errori, cioè non stanno lavorando insieme.

Perdona la mia ignoranza, non mi piace troppo con le API di Twitter, ma sto imparando abbastanza rapidamente. La documentazione di Tweepy fa davvero schifo e ho fatto un sacco di giri di lettura in rete, non riesco proprio a risolverlo. Se riesco a ottenere questo ordinato, pubblicherò un po 'di documentazione.

So come trasferire i dati in un db MySQL una volta estratto (lo farà invece di stampare sullo schermo) e lo manipolerò in modo che io possa fare cose con esso, è solo uscendo fuori che io sono avendo i problemi con. Qualcuno ha qualche idea o c'è un altro metodo che dovrei prendere in considerazione?

Qualsiasi aiuto davvero apprezzato. Acclamazioni

EDIT:

seguito al suggerimento di @Eric Olson questa mattina; Ho fatto quanto segue

1) Creato un set completamente nuovo di credenziali Oauth da testare. 2) codice Copiato attraverso ad un nuovo script come segue:

Oauth

consumer_key = "(removed)" 
consumer_secret = "(removed)" 
access_key="88394805-(removed)" 
access_secret="(removed)" 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(access_key, access_secret) 
api=tweepy.API(auth) 



# confirm account being used for OAuth 
print ("API NAME IS: ", api.me().name) 
api.update_status("Using Tweepy from the command line") 

La prima volta che ho eseguito lo script, funziona benissimo e aggiorna il mio stato e restituisce il nome API come segue:

>>> 
API NAME IS: Chris Howden 

Poi da quel momento in poi ottengo questo:

Traceback (most recent call last): 
    File "C:/Users/Chris/Dropbox/Uni_2012-3/6CC995 - Independent Studies/Scripts/get Api name and update status.py", line 19, in <module> 
    api.update_status("Using Tweepy frm the command line") 
    File "C:\Python32\lib\site-packages\tweepy-1.4-py3.2.egg\tweepy\binder.py", line 153, in _call 
    raise TweepError(error_msg) 
tweepy.error.TweepError: Twitter error response: status code = 403 

Il l'unica ragione per cui posso vedere perché fa qualcosa di simile è che sta rifiutando il token di accesso generato. Non dovrei aver bisogno di rinnovare il token di accesso dovrei?

risposta

6

Se siete aperti a provare un'altra libreria, si potrebbe dare un colpo rauth. C'è già a Twitter example ma se ti senti pigri e vogliono solo un esempio di lavoro, ecco come mi piacerebbe modificare tale script dimostrativo:

from rauth import OAuth1Service 

# Get a real consumer key & secret from https://dev.twitter.com/apps/new 
twitter = OAuth1Service(
    name='twitter', 
    consumer_key='J8MoJG4bQ9gcmGh8H7XhMg', 
    consumer_secret='7WAscbSy65GmiVOvMU5EBYn5z80fhQkcFWSLMJJu4', 
    request_token_url='https://api.twitter.com/oauth/request_token', 
    access_token_url='https://api.twitter.com/oauth/access_token', 
    authorize_url='https://api.twitter.com/oauth/authorize', 
    base_url='https://api.twitter.com/1/') 

request_token, request_token_secret = twitter.get_request_token() 

authorize_url = twitter.get_authorize_url(request_token) 

print 'Visit this URL in your browser: ' + authorize_url 
pin = raw_input('Enter PIN from browser: ') 

session = twitter.get_auth_session(request_token, 
            request_token_secret, 
            method='POST', 
            data={'oauth_verifier': pin}) 

params = {'screen_name': 'github', # User to pull Tweets from 
      'include_rts': 1,   # Include retweets 
      'count': 10}    # 10 tweets 

r = session.get('statuses/user_timeline.json', params=params) 

for i, tweet in enumerate(r.json(), 1): 
    handle = tweet['user']['screen_name'].encode('utf-8') 
    text = tweet['text'].encode('utf-8') 
    print '{0}. @{1} - {2}'.format(i, handle, text) 

È possibile eseguire questo come-è, ma essere sicuri di aggiornare le credenziali! Questi sono solo a scopo dimostrativo.

Full disclosure, sono il manutentore di rauth.

+0

Asso, grazie per i vostri sforzi. Nel frattempo ho cercato di trovare un altro modo per ottenere tutto ciò che volevo usando il modulo tweepy, ma questo aiuta a capire un po 'meglio un po'. – chowden

+0

Pubblicherò ciò che ho trovato quando è completo. – chowden

5

Riceverai risposta 401, che significa "Non autorizzato". (see HTTP status codes)

Il tuo codice sembra buono. Usare api.user_timeline(screen_name="some_screen_name") funziona per me nel vecchio esempio che ho trovato.

Suppongo che sia necessario autorizzare l'app o che ci sia qualche problema con la configurazione di OAuth.

Forse si pensa che questa già, ma qui è l'esempio di codice breve che ho iniziato da: https://github.com/nloadholtes/tweepy/blob/nloadholtes-examples/examples/oauth.py

+0

Cheers. Ho fatto un po 'più di indagini stamattina e ho aggiunto alcuni risultati aggiuntivi sul post originale ... – chowden

Problemi correlati