我正在尝试从Twitter上大约500个用户名中删除最后1-10条推文。 抓住1个用户时代码效果很好,但在引入一系列用户时会出现问题。
第一个代码是单个用户 - 将从Gavinfree获取最后7条推文并写入CSV
import tweepy
import csv
#Twitter API credentials
consumer_key = "secretcode"
consumer_secret = "secretcode"
access_key = "secretcode"
access_secret = "secretcode"
def get_all_tweets(GavinFree):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
alltweets = []
new_tweets = api.user_timeline(screen_name = GavinFree,count=7)
alltweets.extend(new_tweets)
oldest = alltweets[-1].id - 1
while len(new_tweets) > 0:
print "getting tweets before %s" % (oldest)
new_tweets = api.user_timeline(screen_name = GavinFree,count=7,max_id=10)
alltweets.extend(new_tweets)
oldest = alltweets[-1].id - 1
print "...%s tweets downloaded so far" % (len(alltweets))
outtweets = [[tweet.created_at, tweet.text.encode("utf-8")] for tweet in alltweets]
with open('%s_tweets.csv' % GavinFree ,'wb') as f:
writer = csv.writer(f)
writer.writerow(["created_at","text"])
writer.writerows(outtweets)
pass
if __name__ == '__main__':
#pass in the username of the account you want to download
get_all_tweets("GavinFree")
第二个代码是用户范围 - 将从每个用户获取7条推文并写入CSV并且除了范围之外 - 完全相同。
import tweepy
import csv
#Twitter API credentials
consumer_key = "secretcode"
consumer_secret = "secretcode"
access_key = "secretcode"
access_secret = "secretcode"
handles_list = ["gavinFree","bdunkelman","burnie","ashleyj",]
def get_all_tweets(handles_list):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
alltweets = []
new_tweets = api.user_timeline(screen_name = handles_list,count=10)
alltweets.extend(new_tweets)
oldest = alltweets[-1].id - 1
while len(new_tweets) > 0:
print "getting tweets before %s" % (oldest)
new_tweets = api.user_timeline(screen_name = handles_list,count=10,max_id=10)
alltweets.extend(new_tweets)
oldest = alltweets[-1].id - 1
print "...%s tweets downloaded so far" % (len(alltweets))
outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in alltweets]
with open('%s_tweets.csv' % handles_list, '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("handles_list")
我收到的错误代码是 tweepy.error.TweepError:[(你好消息':对不起,该页面不存在。',u'代码:34)]
我已经检查了用户名并尝试了与 @和而不是。 我只是想知道问题是什么,因为代码34在twitter api页面上显示404错误,但只有在添加范围时才会引入错误。
非常感谢任何见解。
答案 0 :(得分:0)
您将handle_list作为字符串文字传递,并且该函数似乎未被修改以处理列表。
试试这个:
if __name__ == '__main__':
for handle in handles_list:
get_all_tweets(handle)