简体   繁体   中英

Python Twitter Streaming Timeline

****I am trying to obtain information from the twitter timeline of a specific user and I am trying to print the output in Json format, however I am getting an AttributeError: 'str' object has no attribute '_json' . I am new to python so I'm having troubles trying to resolve this so any help would be greatly appreciated. ****

Below shows the code that I have at the moment:

from __future__ import absolute_import, print_function

import tweepy
import twitter

def oauth_login():
    # credentials for OAuth
    CONSUMER_KEY = 'woIIbsmhE0LJhGjn7GyeSkeDiU'
    CONSUMER_SECRET = 'H2xSc6E3sGqiHhbNJjZCig5KFYj0UaLy22M6WjhM5gwth7HsWmi'
    OAUTH_TOKEN = '306848945-Kmh3xZDbfhMc7wMHgnBmuRLtmMzs6RN7d62o3x6i8'
    OAUTH_TOKEN_SECRET = 'qpaqkvXQtfrqPkJKnBf09b48TkuTufLwTV02vyTW1kFGunu'

    # Creating the authentication
    auth = twitter.oauth.OAuth( OAUTH_TOKEN,
                                OAUTH_TOKEN_SECRET,
                                CONSUMER_KEY,
                                CONSUMER_SECRET )
    # Twitter instance
    twitter_api = twitter.Twitter(auth=auth)
    return twitter_api

# LogIn
twitter_api = oauth_login()
# Get statuses
statuses = twitter_api.statuses.user_timeline(screen_name='@ladygaga')
# Print text 

for status in statuses:
    print (status['text']._json)

You seem to be mixing up tweepy with twitter , and are possibly getting a bit confused with methods as a result. The auth process for tweepy , from your code, should go as follows:

import tweepy

def oauth_login():
    # credentials for OAuth
    consumer_key = 'YOUR_KEY'
    consumer_secret = 'YOUR_KEY'
    access_token = 'YOUR_KEY'
    access_token_secret = 'YOUR_KEY'

    # Creating the authentication
    auth = tweepy.OAuthHandler(consumer_key,
                               consumer_secret)
    # Twitter instance
    auth.set_access_token(access_token, access_token_secret)
    return tweepy.API(auth)

# LogIn
twitter_api = oauth_login()
# Get statuses
statuses = twitter_api.user_timeline(screen_name='@ladygaga')

# Print text
for status in statuses:
    print (status._json['text'])

If, as previously mentioned, you want to create a list of tweets, you could do the following rather than everything after # Print text

# Create a list
statuses_list = [status._json['text'] for status in statuses]

And, as mentioned in the comments, you shouldn't every give out your keys publicly. Twitter lets you reset them, which I'd recommend you do as soon as possible - editing your post isn't enough as people can still read your edit history.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM