是否可能获取超过100条推文?

15

使用Twitter4j API获取超过100条推文是否可能?
如果可能,有人能指出如何做吗?


4
@NarendraPathai 我正在尝试让默认计数到100,我已经使用了循环并进行了多次查询,但是我反复得到相同的100条推文集合。因此我想问一下,是否有其他方法可以做到这一点? - Nithish Inpursuit Ofhappiness
7个回答

26

要提供针对您情况的代码示例,需要查看您的代码,但是您可以通过since_idmax_id来实现。

此信息适用于Twitter API。

获取前100条推文:

  1. 找到刚刚检索到的集合中最低的id
  2. 使用设置为您刚刚找到的id的max_id选项执行相同的查询。

获取后100条推文:

  1. 找到刚刚检索到的集合中最高的id
  2. 使用设置为您刚刚找到的id的since_id选项执行相同的查询。

在Twitter4j中,您的Query对象有两个字段,表示上述API选项:sinceIdmaxId


3
将max_id设置为max_id-1,否则您将会重复获取到最后一条推文。 - Fabien

4
以下是获取用户所有推文的方法(或至少最多3200条):
import java.util.*;
import twitter4j.*;
import twitter4j.conf.*;

ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("");
cb.setOAuthConsumerSecret("");
cb.setOAuthAccessToken("");
cb.setOAuthAccessTokenSecret("");

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());

4

您无法一次请求加载超过100条推文,但我不知道您为什么需要这样做,相反,您可以在“无限页面”中加载所有推文,即每次用户滚动列表时加载10个项目。

例如

Query query = new Query("stackoverflow");
query.setCount(10);// sets the number of tweets to return per page, up to a max of 100
QueryResult  result = twitter.search(query);

现在,如果您想加载下一页,这很简单易懂。
if(result.hasNext())//there is more pages to load
{
query = result.nextQuery();
result = twitter.search(query);
}

等等。


这个解决方案可能是最方便的。不幸的是,这个解决方案似乎不能与每个查询一起使用。如果您的查询包含特殊字符,例如 Query query = new Query("*");,那么 result.nextQuery() 就无法正确编码它们,从而导致 Twitter API 返回一个错误信息 "could not authenticate you"。 - asmaier

4

一些Java代码通过使用最低ID迭代到旧页面可能是这样的:

Query query = new Query("test");
query.setCount(100);

int searchResultCount;
long lowestTweetId = Long.MAX_VALUE;

do {
    QueryResult queryResult = twitterInstance.search(query);

    searchResultCount = queryResult.getTweets().size();

    for (Status tweet : queryResult.getTweets()) {

        // do whatever with the tweet

        if (tweet.getId() < lowestTweetId) {
            lowestTweetId = tweet.getId();
            query.setMaxId(lowestTweetId);
        }
    }

} while (searchResultCount != 0 && searchResultCount % 100 == 0);

2

除了Luke的方法之外,Twitter4j提供了对查询结果进行分页的功能。您可以尝试为查询获取多个页面。设置每页结果数量和页面号码。

但我建议先尝试since_id,然后再尝试分页。


1
当您获得包含前100个结果的响应时,响应中还会包含下一个id。可以将该id用作查询参数“next”= {从上一次调用收到的id},再次进行调用,它将为您提供接下来的100条推文。

0

对于给定的查询,可以提取超过100条推文。您可以下载一个Twitter GUI应用程序进行快速演示,以从http://preciselyconcise.com/apis_and_installations/tweets_extraction_from_twitter.php中提取推文。

通过从该查询的所有可用页面提取查询结果,如果在该查询下可用,则可以提取超过100条推文。我下载了该网站上提供的GUI应用程序,并能够为查询#happy提取超过1000条推文。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接