简体   繁体   中英

Using Python with Twitter API (Getting 215 error)

I'm new to using APIs and I'm trying to simply use the twitter API to search for tweets. I followed the development guide on twitter, but it's still giving this json code. {u'errors': [{u'message': u'Bad Authentication data', u'code': 215}]}

consumer_key = xxx
consumer_secret = yyy
token = base64.b64encode(consumer_key + ":" + consumer_secret)
headers = {'Authorization' : 'Basic ' + token, 'Content-Type' : 'application/x-www-form-urlencoded;charset=UTF-8'}
data = {'grant_type' : 'client_credentials'}
url = 'https://api.twitter.com/oauth2/token'
resp = requests.post(url, data = data, headers=headers)  
d = resp.json()
access_token = 'Bearer ' + d['access_token']

tweets = requests.get('https://api.twitter.com/1.1/search/tweets.json?q=python')

Any advice?

The Twitter API does not allow access without authentication, you might have problems with the credentials, check this article that explains AUTHENTICATING Twitter API.

One more thing, try to use Tweepy , it's an easy-to-use Python library for accessing the Twitter API.

Here's a quick example on how to use it. It seems that you were fetching all the tweets related to Python .

For more details

import tweepy 
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json


#Use your keys
consumer_key = '...'
consumer_secret = '...' 
access_token = '...'
access_secret = '...'


auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)


class TweetListener(StreamListener):
    def on_status(self, status):
      print "tweet " + str(status.created_at) +"\n"
      print status.text + "\n"
      # You can dump your tweets into Json File, or load it to your database

stream = Stream(auth, TweetListener(), secure=True, )
t = u"#python" # You can use different hashtags 
stream.filter(track=[t])

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