How can I retrieve all Tweets and attributes for a given user using Python?

前端 未结 2 1176
故里飘歌
故里飘歌 2020-12-31 11:04

I am attempting to retrieve data from Twitter, using Tweepy for a username typed at the command line. I\'m wanting to extract quite a bit of data about the status and user,s

相关标签:
2条回答
  • 2020-12-31 11:31

    You're getting 401 response, which means "Unauthorized." (see HTTP status codes)

    Your code looks good. Using api.user_timeline(screen_name="some_screen_name") works for me in the old example I have lying around.

    I'm guessing you either need to authorize the app, or there is some problem with your OAuth setup.

    Maybe you found this already, but here is the short code example that I started from: https://github.com/nloadholtes/tweepy/blob/nloadholtes-examples/examples/oauth.py

    0 讨论(0)
  • 2020-12-31 11:38

    If you're open to trying another library, you could give rauth a shot. There's already a Twitter example but if you're feeling lazy and just want a working example, here's how I'd modify that demo script:

    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)
    

    You can run this as-is, but be sure to update the credentials! These are meant for demo purposes only.

    Full disclosure, I am the maintainer of rauth.

    0 讨论(0)
提交回复
热议问题