2017-06-13 63 views
0

我写了这个代码来获取Twitter帐户的追随者的完整列表使用Tweepy:如何获得并保存到文件Twitter帐户的追随者的完整列表,与Tweepy

# ... twitter connection and streaming 

fulldf = pd.DataFrame() 
line = {} 
ids = [] 
try: 
    for page in tweepy.Cursor(api.followers_ids, screen_name="twittername").pages(): 
     df = pd.DataFrame() 
     ids.extend(page) 
     try: 
      for i in ids: 
       user = api.get_user(i) 

       line = [{'id': user.id, 
       'Name': user.name, 
       'Statuses Count':user.statuses_count, 
       'Friends Count': user.friends_count, 
       'Screen Name':user.screen_name, 
       'Followers Count':user.followers_count, 
       'Location':user.location, 
       'Language':user.lang, 
       'Created at':user.created_at, 
       'Time zone':user.time_zone, 
       'Geo enable':user.geo_enabled, 
       'Description':user.description.encode(sys.stdout.encoding, errors='replace')}] 
       df = pd.DataFrame(line) 
       fulldf = fulldf.append(df) 
       del df 
       fulldf.to_csv('out.csv', sep=',', index=False) 
       print i ,len(ids) 
     except tweepy.TweepError: 
      time.sleep(60 * 15) 
      continue 
except tweepy.TweepError as e2: 
    print "exception global block" 
    print e2.message[0]['code'] 
    print e2.args[0][0]['code'] 

最后我只有1000线在csv文件中,将所有内容保存在内存(dataframe)并将其保存到相同的循环中并不是最佳解决方案。但至少我有一些工作,但没有得到15000名追随者中的1000人。

任何帮助,这将不胜感激。

+0

有些机会是''例外全局块''打印? – asongtoruin

+0

是的,我不是专家,所以我只想知道它在哪里发生。但这不是问题,我认为这是将数据保存到文件中的问题。 – lazurens

+0

我认为这与你试图捕捉错误的方式有关。如果你当时没有答案,我今天晚上会看看它。 – asongtoruin

回答

2

考虑你的代码的以下部分:

for page in tweepy.Cursor(api.followers_ids, screen_name="twittername").pages(): 
     df = pd.DataFrame() 
     ids.extend(page) 
     try: 
      for i in ids: 
       user = api.get_user(i) 

当您使用extend的每一页,只需添加新集ID到您的ids列表的末尾。你嵌套你的for声明的方式意味着你返回的每一个新页面,你的所有前面的页面,你get_user首先 - 因此,当你打到ids的最后一页时,你仍然在看第一个1000左右当你达到费率限制并且没有更多页面浏览时。你也可能达到你的游标速度限制,这就是你看到这个例外的原因。

让我们从头开始。

首先,当您使用wait_on_rate_limit创建API时,tweepy可以为您处理速率限制(主要错误来源之一)。这解决了一大堆问题,所以我们会这样做。其次,如果使用lookup_users,则每个请求可以查找100个用户对象。我在another answer中写过这个,所以我从那里采取了这种方法。

最后,我们不需要创建数据框或导出到csv直到最后。如果我们获得用户信息词典的列表,则可以很快更改为DataFrame,而我们没有真正努力。

下面是完整的代码 - 您需要将钥匙和用户的用户名实际查找,但除此之外,希望它能够正常工作!

import tweepy 
import pandas as pd 

def lookup_user_list(user_id_list, api): 
    full_users = [] 
    users_count = len(user_id_list) 
    try: 
     for i in range((users_count/100) + 1): 
      print i 
      full_users.extend(api.lookup_users(user_ids=user_id_list[i * 100:min((i + 1) * 100, users_count)])) 
     return full_users 
    except tweepy.TweepError: 
     print 'Something went wrong, quitting...' 

consumer_key = 'XXX' 
consumer_secret = 'XXX' 
access_token = 'XXX' 
access_token_secret = 'XXX' 

auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(access_token, access_token_secret) 

api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) 

ids = [] 
for page in tweepy.Cursor(api.followers_ids, screen_name="twittername").pages(): 
    ids.extend(page) 

results = lookup_user_list(ids, api) 
all_users = [{'id': user.id, 
      'Name': user.name, 
      'Statuses Count': user.statuses_count, 
      'Friends Count': user.friends_count, 
      'Screen Name': user.screen_name, 
      'Followers Count': user.followers_count, 
      'Location': user.location, 
      'Language': user.lang, 
      'Created at': user.created_at, 
      'Time zone': user.time_zone, 
      'Geo enable': user.geo_enabled, 
      'Description': user.description} 
      for user in results] 

df = pd.DataFrame(all_users) 

df.to_csv('All followers.csv', index=False, encoding='utf-8') 
+0

我编辑了我的代码,并使用了您所建议的优化,现在我正在运行脚本,这似乎是一个很好的解决方案。感谢您的努力@ason​​gtoruin以及您投资改善代码的时间。我很感激。 – lazurens

+0

@lazurens不用担心朋友!如果您发现它有用,您可以用答案左侧的勾号将其标记为问题的答案 – asongtoruin

+0

这确实是我的答案,并且它修复了我没有足够声望来点击thubms的所有信息。再次感谢你。 – lazurens

相关问题