从Twitter账户获取信息
我正在尝试编写代码,从我的推特账户获取信息。我使用的是tweetPy这个接口。我用的代码如下:
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)
第二个问题是在这一行 user = tweepy.api.get_user('username'),我想获取我账户的好友列表,但我得到的却是:
tweepy.error.TweepError: [{u'message': u'Bad Authentication data', u'code': 215}]
1 个回答
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")
现在应该可以正常工作了。