【问题标题】:How to resolve this error in python script for extracting twitter tweets如何在用于提取 Twitter 推文的 python 脚本中解决此错误
【发布时间】:2018-12-18 00:59:44
【问题描述】:

我使用的是 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

【问题讨论】:

  • 你的代码是没有被识别的,还是只是在复制它的时候它没有缩进?

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


【解决方案1】:

尝试用大写字母写,我遇到了这个错误,这就是我修复它的方法。

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

【讨论】:

    猜你喜欢
    • 2021-03-02
    • 2013-08-20
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 2018-01-18
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多