2016-04-29 9 views
0

私はこれに関して尋ねられた同様の質問を知っていますが、私が作業しているプロジェクトはTweepy for Pythonを使用しているため、少し具体的です。Tweepyで複数のユーザーから複数のつぶやきを収集するにはどうすればよいですか?

私はコークスとペプシのフォロワーから1000人のユーザーIDを収集し、それぞれのユーザーの最新の20のステータスを検索し、使用されたハッシュタグを収集します。

私はTweepy followers_idsとuser_timeline APIを使用していますが、私はTwitterから401を取得し続けています。私が1000の代わりに10だけに検索するユーザーIDの数を設定すると、私は時々私が望む結果を得ることができますが、それでも私は401を取得することもあります。だからそれは働く.... 種類の。それはこれらのエラーの原因となっている大規模なセットのようだと私はそれらを回避する方法を知らない。

Twitterにはコールに制限があることは知っていますが、1000ユーザーIDを取得することができれば、どうして私のステータスを取得できないのですか?私は20,000のステータスを取得しようとしていることを認識していますが、私は100 * 20、さらには50 * 20でこれを試しましたが、まだ401を取得しています。私はシステムクロックを何回もリセットしましたが、それは時々10 * 20のセットでしか動作しません。私はこれまでのところよりも優れた、効率的な方法があるかもしれないと思っています。私はTwitter APIの初心者であり、Pythonにはかなり新しいので、うまくいけば私だけです。ここで

はコードです:

import tweepy 
import pandas as pd 

consumer_key = 'REDACTED' 
consumer_secret = 'REDACTED' 
access_token = 'REDACTED' 
access_token_secret = 'REDACTED' 

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

api = tweepy.API(auth) 

pepsiUsers = [] 
cokeUsers = [] 
cur_pepsiUsers = tweepy.Cursor(api.followers_ids, screen_name='pepsi') 
cur_cokeUsers = tweepy.Cursor(api.followers_ids, screen_name='CocaCola') 

for user in cur_pepsiUsers.items(1000): 
    pepsiUsers.append({ 'userId': user, 'hTags': [], 'favSoda': 'Pepsi' }) 
    for status in tweepy.Cursor(api.user_timeline, user).items(20): 
     status = status._json 
     hashtags = status['entities']['hashtags'] 
     index = len(pepsiUsers) - 1 
     if len(hashtags) > 1: 
      for ht in hashtags: 
       pepsiUsers[index]['hTags'].append(ht['text']) 

for user in cur_cokeUsers.items(1000): 
    cokeUsers.append({ 'userId': user, 'hTags': [], 'favSoda': 'Coke' }) 
    for status in tweepy.Cursor(api.user_timeline, user).items(20): 
     status = status._json 
     hashtags = status['entities']['hashtags'] 
     index = len(cokeUsers) - 1 
     if len(hashtags) > 1: 
      for ht in hashtags: 
       cokeUsers[index]['hTags'].append(ht['text']) 

"""create a master list of coke and pepsi users to write to CSV""" 
mergedList = cokeUsers + pepsiUsers 
"""here we'll turn empty hashtag lists into blanks and turn all hashtags for each user into a single string 
    for easier searching with R later""" 
for i in mergedList: 
    if len(i['hTags']) == 0: 
     i['hTags'] = '' 
    i['hTags'] = ''.join(i['hTags']) 

list_df = pd.DataFrame(mergedList, columns=['userId', 'favSoda', 'hTags']) 
list_df.to_csv('test.csv', index=False) 

そして、ここで私が

--------------------------------------------------------------------------- 
TweepError        Traceback (most recent call last) 
<ipython-input-134-a7658ed899f3> in <module>() 
     3 for user in cur_pepsiUsers.items(1000): 
     4  pepsiUsers.append({ 'userId': user, 'hTags': [], 'favSoda': 'Pepsi' }) 
----> 5  for status in tweepy.Cursor(api.user_timeline, user).items(20): 
     6   status = status._json 
     7   hashtags = status['entities']['hashtags'] 

/Users/.../anaconda/lib/python3.5/site-packages/tweepy/cursor.py in __next__(self) 
    47 
    48  def __next__(self): 
---> 49   return self.next() 
    50 
    51  def next(self): 

/Users/.../anaconda/lib/python3.5/site-packages/tweepy/cursor.py in next(self) 
    195   if self.current_page is None or self.page_index == len(self.current_page) - 1: 
    196    # Reached end of current page, get the next page... 
--> 197    self.current_page = self.page_iterator.next() 
    198    self.page_index = -1 
    199   self.page_index += 1 

/Users/.../anaconda/lib/python3.5/site-packages/tweepy/cursor.py in next(self) 
    106 
    107   if self.index >= len(self.results) - 1: 
--> 108    data = self.method(max_id=self.max_id, parser=RawParser(), *self.args, **self.kargs) 
    109 
    110    if hasattr(self.method, '__self__'): 

/Users/.../anaconda/lib/python3.5/site-packages/tweepy/binder.py in _call(*args, **kwargs) 
    243    return method 
    244   else: 
--> 245    return method.execute() 
    246 
    247  # Set pagination mode 

/Users/.../anaconda/lib/python3.5/site-packages/tweepy/binder.py in execute(self) 
    227      raise RateLimitError(error_msg, resp) 
    228     else: 
--> 229      raise TweepError(error_msg, resp, api_code=api_error_code) 
    230 
    231    # Parse the response payload 

TweepError: Twitter error response: status code = 401 
+0

[401 HTTPステータス](https://httpstatuses.com/401)の意味から始めます。あなたのコードに何も問題はないかもしれません。あなたはちょうどTwitterによって課された制限内で生きなければならないでしょう。 – ChrisP

+0

私は401が何であるかを理解していますが、Twitter APIが401の理由を返すことができることも知っています。ここで起こっていることは(これは私の無教授の推測です)多くのコールは時間がかかりすぎるため、サーバーを呼び出すことはもはやTwitterと同期していません。私はTweepyがページングを提供していることを知っていますが、私はここでそれをどのように使用するかを完全には理解していません。 – visarts

+0

リストの作成、リストへのユーザーの追加、リスト内のツイートの読み込みをお勧めします。 – ahmad

答えて

1

はあなただけ必要ですapi.user_timelineコードを実行するブロック用のものを実行しようとすると、私は取得していますエラーですTwitter JSON?あなたの収集エリアの範囲のために、あなたはtwarcを試してみることができます:https://github.com/edsu/twarc

関連する問題