前提
指定したツイートに付随するリプライを抽出したいのですが、リプライの内容と数が正しく表示されません。お知恵をお貸しいただければ幸いです。よろしくお願いします。
実現したいこと
リプライ数とリプライ本文を正確に表示する
現在の出力結果
検索回数 : 101 リプライ数 : 0 []
理想の出力結果(例)
検索回数 : 50 リプライ数 : 721 @nikkei 一律200円‥?何か納得できない。モヤモヤする。 @nikkei 数日繋がらないだけで1ヶ月分無料にしてもらおうとしたり+αの誠意見せろとか言ってるの怖すぎ ...
該当のソースコード
python
1#!/usr/bin/env python 2# coding: utf-8 3 4import urllib 5from requests_oauthlib import OAuth1Session, OAuth1 6import requests 7import sys 8 9def main(): 10 11 # APIの秘密鍵 12 CK = '****' 13 CKS = '****' 14 AT = '****' 15 ATS = '****' 16 # ユーザー・ツイートID 17 user_id = '@@nikkei' 18 tweet_id = '1552907364113625089' # str型で指定 19 # 検索時のパラメーター 20 count = 15 # 一回あたりの検索数(最大100/デフォルトは15) 21 range = 100 # 検索回数の上限値(最大180/15分でリセット) 22 # ツイート検索・リプライの抽出 23 tweets = search_tweets(CK, CKS, AT, ATS, user_id, tweet_id, count, range) 24 # 抽出結果を表示 25 print(tweets[0:750]) 26 27 28def search_tweets(CK, CKS, AT, ATS, user_id, tweet_id, count, range): 29 # 文字列設定 30 user_id += ' exclude:retweets' # RTは除く 31 user_id = urllib.parse.quote_plus(user_id) 32 # リクエスト 33 url = "https://api.twitter.com/1.1/search/tweets.json?lang=ja&q="+user_id+"&count="+str(count) 34 auth = OAuth1(CK, CKS, AT, ATS) 35 response = requests.get(url, auth=auth) 36 data = response.json()['statuses'] 37 # 2回目以降のリクエスト 38 cnt = 0 39 reply_cnt = 0 40 tweets = [] 41 while True: 42 if len(data) == 0: 43 break 44 cnt += 1 45 if cnt > range: 46 break 47 for tweet in data: 48 if tweet['in_reply_to_status_id_str'] == tweet_id: # ツイートIDに一致するものを抽出 49 tweets.append(tweet['text']) # ツイート内容 50 reply_cnt += 1 51 maxid = int(tweet["id"]) - 1 52 url = "https://api.twitter.com/1.1/search/tweets.json?lang=ja&q="+user_id+"&count="+str(count)+"&max_id="+str(maxid) 53 response = requests.get(url, auth=auth) 54 try: 55 data = response.json()['statuses'] 56 except KeyError: # リクエスト回数が上限に達した場合のデータのエラー処理 57 print('上限まで検索しました') 58 break 59 print('検索回数 :', cnt) 60 print('リプライ数 :', reply_cnt) 61 return tweets 62 63 64if __name__ == '__main__': 65 main()
補足情報(FW/ツールのバージョンなど)
Macbook Pro, MacOS Ventura 13.0.1, Python 3.9.7., Virtual Studio Code
あなたの回答
tips
プレビュー