如何获取超过15条推文?Node.js的Twitter npm包查询问题
解决Twitter API获取超过15条推文的问题
嘿,这问题我熟!你现在只能拿到15条推文,是因为Twitter的Search API默认返回15条结果,而且你没在请求里指定要更多的数量。下面分两步帮你搞定:
1. 单次请求获取最多100条推文
Twitter的Search API单次请求最多支持返回100条结果,你只需要在请求参数里加上count字段,指定你想要的数量(最大100)。
修改你的代码如下:
app.get('/', function (req, res) { res.writeHead(200, {"Content-Type": "text/html; charset=utf-8"}); // 加上count参数,这里设为100(单次请求上限) client.get('search/tweets', {q: hashTags, count: 100}, function(error, tweets, response) { if (!error) { var size = tweets.statuses.length; console.log(`当前返回推文数量:${size}`); for(var i = 0; i<size; i++){ res.write(/* 你的推文渲染逻辑 */); } res.end(); } else { console.error('请求出错:', error); res.end('获取推文失败'); } }); });
2. 获取超过100条推文(分页处理)
如果需要拿到100条以上的推文,就得用分页机制:Twitter API会在返回结果的search_metadata里提供next_results参数,里面包含了下一页请求需要的max_id(用来获取比当前结果更早的推文)。
这里给你一个简单的分页实现示例,递归请求直到拿到足够数量的推文:
// 定义一个函数来递归获取推文 function fetchTweets(queryParams, accumulatedTweets = [], desiredCount = 200) { return new Promise((resolve, reject) => { client.get('search/tweets', queryParams, function(error, tweets, response) { if (error) { console.error('分页请求出错:', error); reject(error); return; } // 累加当前页的推文 accumulatedTweets = accumulatedTweets.concat(tweets.statuses); // 检查是否已经拿到足够数量,或者没有更多结果 if (accumulatedTweets.length >= desiredCount || !tweets.search_metadata.next_results) { console.log(`最终获取推文总数:${accumulatedTweets.length}`); resolve(accumulatedTweets); return; } // 解析next_results里的max_id参数,构造下一页的请求参数 const nextParams = new URLSearchParams(tweets.search_metadata.next_results.slice(1)); const nextQueryParams = { q: queryParams.q, count: 100, max_id: nextParams.get('max_id') }; // 递归请求下一页 fetchTweets(nextQueryParams, accumulatedTweets, desiredCount) .resolve(resolve) .catch(reject); }); }); } // 在路由里调用这个函数 app.get('/', function (req, res) { res.writeHead(200, {"Content-Type": "text/html; charset=utf-8"}); // 初始请求参数,指定要获取200条(可按需修改) fetchTweets({q: hashTags, count: 100}, [], 200) .then(tweets => { // 渲染所有推文到响应 tweets.forEach(tweet => { res.write(/* 你的推文渲染逻辑 */); }); res.end(); }) .catch(err => { res.end('获取推文失败'); }); });
注意事项
- API速率限制:Twitter API有调用次数限制,频繁分页请求可能会触发限流,记得处理相关错误。
- count上限:单次请求的
count参数最大只能设为100,设置超过100也只会返回100条。 - max_id的作用:
max_id会返回ID小于等于该值的推文,确保不会重复获取已经拿到的内容。
内容的提问来源于stack exchange,提问作者CMartins
相关产品推荐
相关产品推荐

