从Twitter帐户中检索信息

时间:2014-04-29 07:12:03

标签: python twitter

我正在尝试创建代码以从我的Twitter帐户返回信息。我正在使用tweetPy api。我使用的代码如下:

CONSUMER_KEY = "..."
CONSUMER_SECRET ="..."
OAUTH_TOKEN ="..-..."
OAUTH_SECRET ="..."
import tweepy

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(OAUTH_TOKEN, OAUTH_SECRET)

api = tweepy.API(auth)
fp = codecs.open("Tweets.txt", "w", "utf-8")
public_tweets = api.home_timeline()
for tweet in public_tweets:
  tweet.text.encode('utf8')
  fp.write(tweet.text) 
  #print (tweet.text)

 # Get the User object for twitter...
 user = tweepy.api.get_user("twitter")  

 print user.screen_name
 print user.followers_count
 for friend in user.friends():
     print friend.screen_name

我有两个问题。首先,我能够将tweet.text写入文件,但是当我尝试打印结果时出现错误。我得到了:

    print (tweet.text)
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-6: ordinal not in range(128)

第二个问题是用户行= tweepy.api.get_user('用户名'),我正在尝试返回我帐户的frient_list,但是我得到了:

tweepy.error.TweepError: [{u'message': u'Bad Authentication data', u'code': 215}]

1 个答案:

答案 0 :(得分:3)

对于Unicode错误,最好在Python脚本中更好地使用Unicode,因为Twitter使用Unicode字符集。为此,您可以在Python脚本的开头执行以下操作 -

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

对于Bad Authentication data错误,请替换以下行 -

user = tweepy.api.get_user("twitter")

user = api.get_user("twitter")

现在应该可以了。