如何解决用于提取Twitter Tweets的python脚本中的此错误

时间:2018-07-10 08:46:13

标签: python python-3.x python-2.7 twitter

我正在使用python3,但此处的代码适用于python2。运行代码时出现错误。我必须从推特上获取推文。 我已经安装了tweepy,但是仍然出现错误。 我的访问密钥,消费者密钥和消费者秘密密钥是正确的。我该如何解决这个问题。是解决此问题的替代方法吗?

import tweepy #https://github.com/tweepy/tweepy
import csv

#Twitter API credentials
consumer_key = "xxxx"
consumer_secret = "xxxx"
access_key = "xxxx"
access_secret = "xxxx"


def get_all_tweets(screen_name):
#Twitter only allows access to a users most recent 3240 tweets with this method

#authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)

#initialize a list to hold all the tweepy Tweets
alltweets = []

#make initial request for most recent tweets (200 is the maximum allowed count)
new_tweets = api.user_timeline(screen_name,count=200)

#save most recent tweets
alltweets.extend(new_tweets)

#save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1

#keep grabbing tweets until there are no tweets left to grab
while len(new_tweets) > 0:
print ("getting tweets before %s" % (oldest))

#all subsiquent requests use the max_id param to prevent duplicates
new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)
#save most recent tweets
alltweets.extend(new_tweets)`enter code here`

#update the id of the oldest tweet less one
oldest = alltweets[-1].id - 1

print("...%s tweets downloaded so far" % (len(alltweets)))

#transform the tweepy tweets into a 2D array that will populate the csv 
outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in alltweets]
#write the csv
with open('%s_tweets.csv' % screen_name, 'wb') as f:
writer = csv.writer(f)
writer.writerow(["id","created_at","text"])
writer.writerows(outtweets)


pass


if __name__ == '__main__':
#pass in the username of the account you want to download
get_all_tweets("ArsalanBajwa")

'


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-e2a778291283> in <module>()
     21 
     22 #make initial request for most recent tweets (200 is the maximum allowed count)
---> 23 new_tweets = api.user_timeline(screen_name,count=200)
     24 
     25 #save most recent tweets

NameError: name 'api' is not defined

how to resolve it?

Api

1 个答案:

答案 0 :(得分:0)

尝试用大写字母写出来,我遇到了这个错误,这就是我解决的方法。

new_tweets = API.user_timeline(screen_name,count = 200)