Created
November 13, 2020 12:22
-
-
Save sugaryo/866e3a32f1b91ba972f90eeabbc5e7ee to your computer and use it in GitHub Desktop.
TwitterAPI(twitter4jライブラリ)で検索ページングする方法。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import twitter4j.Query; | |
import twitter4j.QueryResult; | |
import twitter4j.Status; | |
import twitter4j.Twitter; | |
import twitter4j.TwitterException; | |
// search | |
/** | |
* Twitter API SearchQuery(with paging) のサンプルコード. | |
* <p> | |
* {@link SearchResource#search(Query)} を使用したページング処理のサンプルコード。<br> | |
* 検索処理はページサイズとページ上限を指定できます(デフォルトは5件10ページ)。 | |
* </p> | |
* | |
* @param query 検索クエリ | |
* @return 検索結果 | |
* | |
* @see #search(String, int, int) | |
* @see twitter4j.Query | |
* @see twitter4j.QueryResult | |
* @see twitter4j.QueryResult#hasNext() | |
* @see twitter4j.QueryResult#nextQuery() | |
* @see twitter4j.api.SearchResource#search(Query) | |
*/ | |
public List<Status> search( final String query ) { | |
return this.search( query, 5, 10 ); | |
} | |
/** | |
* Twitter API SearchQuery(with paging) のサンプルコード. | |
* <p> | |
* {@link SearchResource#search(Query)} を使用したページング処理のサンプルコード。<br> | |
* 検索処理はページサイズとページ上限を指定できます(デフォルトは5件10ページ)。 | |
* </p> | |
* | |
* @param query 検索クエリ | |
* @param pageSize ページサイズ<b>;1ページあたりのツイート数</b> | |
* @param pageLimit ページ上限<b>;ページングのループ処理上限</b> | |
* @return 検索結果 | |
* | |
* @see twitter4j.Query | |
* @see twitter4j.QueryResult | |
* @see twitter4j.QueryResult#hasNext() | |
* @see twitter4j.QueryResult#nextQuery() | |
* @see twitter4j.api.SearchResource#search(Query) | |
*/ | |
public List<Status> search( | |
final String query, | |
final int pageSize, | |
final int pageLimit ) { | |
List<Status> tweets = new ArrayList<>(); | |
try { | |
// q.count : the number of tweets to return per page. | |
var q = new Query( query ).count( pageSize ); | |
for ( int i = 0; i < pageLimit; i++ ) { | |
final QueryResult result = this.twitter.search( q ); | |
final List<Status> searched = result.getTweets(); | |
tweets.addAll( searched ); | |
log.info( "page[{}] : {}" | |
, i | |
, searched.stream().map( x -> x.getId() ).toArray( Long[]::new ) | |
); | |
// ■まだある場合は次のページクエリを取り出してループを回す。 | |
if ( result.hasNext() ) { | |
q = result.nextQuery(); | |
// 実際はこのへんでThread.sleepした方が良いとか色々あるけど割愛。 | |
} | |
// ■もうない場合はループを抜ける。 | |
else { | |
break; | |
} | |
} | |
} | |
// 検査例外はRuntimeでくるんでポイ。 | |
catch ( TwitterException ex ) { | |
throw new RuntimeException( ex ); | |
} | |
return tweets; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment