great084 / twitter_tool

ツイッターツールの開発
0 stars 0 forks source link

[機能追加]100件以上のツイート取得(1回のリクエストにて取得できる最大件数) #31

Closed domi10momo closed 3 years ago

domi10momo commented 3 years ago

概要

実装内容

100件以上取得ツイートがある場合、1回目のAPIの戻り値に["next"]パラメータが付加される(トークン形式) このパラメータを使用し、解決ができそうです。

(現状) 戻り値から["next"]パラメータを取得し、クエリに追加してみたが、API取得2週目が走っても同じ100件のツイートしか取得できない。

(考えられる原因の候補)

その他情報

Twitter developer Documentation

【難解!?】Twitter APIを使ってツイッターの投稿データを収集する方法

great084 commented 3 years ago

@domi10momo 最大件数を超えた場合、以下のようにnextパラメータを次のリクエストのクエリに指定することで、前回完了部分から取得できました。 実行したのは、curlコマンドで実行してみました。 パラメータと、レスポンスのみ抜粋します。

初回のリクエスト

{
                "query":"from:Samayouseijin lang:ja",
                "maxResults": "11",
                "fromDate":"201908010000", 
                "toDate":"202012042359
}
...
"next": "eyJtYXhJZCI6MTIzODI4OTExNTY4ODIzMDkxMn0=",    # ←このnextのトークンを次回のリクエスト時に指定
  "requestParameters": {
    "maxResults": 11,
    "fromDate": "201908010000",
    "toDate": "202012042359"
  }

2回目のリクエスト

{
                "query":"from:Samayouseijin lang:ja",
                "maxResults": "11",
                "fromDate":"201908010000", 
                "toDate":"202012042359",
                "next":"eyJtYXhJZCI6MTIzODI4OTExNTY4ODIzMDkxMn0=" # ←前回responseのnextのトークンをクエリに指定
}
...
  "next": "eyJtYXhJZCI6MTIzMDMyOTU5MjQ5OTQzMzQ3M30=",   # ←あれば次のリクエストで指定する(繰り返し)
  "requestParameters": {
    "maxResults": 11,
    "fromDate": "201908010000",
    "toDate": "202012042359"
  }
great084 commented 3 years ago

@domi10momo 参考にしたドキュメントです。

https://developer.twitter.com/en/docs/twitter-api/v1/tweets/search/api-reference/premium-search#Pagination の以下の部分

If your query matches more Tweets than the 'maxResults' parameter used in the request, the response will include a 'next' token (as a root-level JSON attribute). This 'next' token can be used in a subsequent request to retrieve the next portion of the matching Tweets for that query (i.e. the next 'page'). Next tokens will continue to be provided until you have reached the last “page” of results for that query when no 'next' token is provided.

また、以下の内容を読むと、このnextトークンは期限がないので、いつやっても同じ結果が来るとのこと。 これは、最大リクエスト回数超えた場合でもトークン保存しておけば使えそうですね・・・

The 'next' token does not expire. Multiple requests using the same 'next' query will receive the same results, regardless of when the request is made. Be sure to always update the 'next' token as you paginate through the results.