我有一份推特用户名单,这些用户的个人资料是公开的。我希望能获取他们从创建账号那天起发布的“所有推文”。我在GitHub上检查了Twitter4J示例。GitHub链接 根据Twitter API文档,只会返回最近的20条推文。是否有任何方法可以完成我的任务?
我有一份推特用户名单,这些用户的个人资料是公开的。我希望能获取他们从创建账号那天起发布的“所有推文”。我在GitHub上检查了Twitter4J示例。GitHub链接 根据Twitter API文档,只会返回最近的20条推文。是否有任何方法可以完成我的任务?
要使用Twitter4J获取用户的所有帖子,您需要在多个页面上进行请求。
以下代码基于GitHub上的示例。
Twitter unauthenticatedTwitter = new TwitterFactory().getInstance();
//First param of Paging() is the page number, second is the number per page (this is capped around 200 I think.
Paging paging = new Paging(1, 100);
List<Status> statuses = unauthenticatedTwitter.getUserTimeline("google",paging);
只需循环并不断获取新页面,直到没有新帖子为止应该就可以了。
以下是获取用户的所有推文(或至少高达~3200条)的方法:
import java.util.*;
import twitter4j.*;
import twitter4j.conf.*;
public static void main(String[] a) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("YOUR KEYS HERE");
cb.setOAuthConsumerSecret("YOUR KEYS HERE");
cb.setOAuthAccessToken("YOUR KEYS HERE");
cb.setOAuthAccessTokenSecret("YOUR KEYS HERE");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
int pageno = 1;
String user = "cnn";
List statuses = new ArrayList();
while (true) {
try {
int size = statuses.size();
Paging page = new Paging(pageno++, 100);
statuses.addAll(twitter.getUserTimeline(user, page));
if (statuses.size() == size)
break;
}
catch(TwitterException e) {
e.printStackTrace();
}
}
System.out.println("Total: "+statuses.size());
}
http://api.twitter.com/1/statuses/user_timeline.xml?id=SomeUsername&count=200&page=1
http://api.twitter.com/1/statuses/user_timeline.xml?id=SomeUsername&count=200&page=2
http://api.twitter.com/1/statuses/user_timeline.xml?id=SomeUsername&count=200&page=3
请记住,这些请求受到速率限制,因此您需要小心,不要超过限制。