【发布时间】:2015-11-24 10:22:39
【问题描述】:
我正在尝试通过提供主题标签和时间范围(自和直到日期)来查询来自 Instagram 的帖子。 我使用recent tags endpoint。
https://api.instagram.com/v1/tags/{tag-name}/media/recent?access_token=ACCESS-TOKEN
我的代码是使用 instagram-node 库在 Node.js 中编写的(请参阅内联 cmets):
// Require the config file
var config = require('../config.js');
// Require and intialize the instagram instance
var ig = require('instagram-node').instagram();
// Set the access token
ig.use({ access_token: config.instagram.access_token });
// We export this function for public use
// hashtag: the hashtag to search for
// minDate: the since date
// maxDate: the until date
// callback: the callback function (err, posts)
module.exports = function (hashtag, minDate, maxDate, callback) {
// Create the posts array (will be concated with new posts from pagination responses)
var posts = [];
// Convert the date objects into timestamps (seconds)
var sinceTime = Math.floor(minDate.getTime() / 1000);
var untilTime = Math.floor(maxDate.getTime() / 1000);
// Fetch the IG posts page by page
ig.tag_media_recent(hashtag, { count: 50 }, function fetchPosts(err, medias, pagination, remaining, limit) {
// Handle error
if (err) {
return callback(err);
}
// Manually filter by time
var filteredByTime = medias.filter(function (currentPost) {
// Convert the created_time string into number (seconds timestamp)
var createdTime = +currentPost.created_time;
// Check if it's after since date and before until date
return createdTime >= sinceTime && createdTime <= untilTime;
});
// Get the last post on this page
var lastPost = medias[medias.length - 1] || {};
// ...and its timestamp
var lastPostTimeStamp = +(lastPost.created_time || -1);
// ...and its timestamp date object
var lastPostDate = new Date(lastPostTimeStamp * 1000);
// Concat the new [filtered] posts to the big array
posts = posts.concat(filteredByTime);
// Show some output
console.log('found ' + filteredByTime.length + ' new items total: ' + posts.length, lastPostDate);
// Check if the last post is BEFORE until date and there are no new posts in the provided range
if (filteredByTime.length === 0 && lastPostTimeStamp <= untilTime) {
// ...if so, we can callback!
return callback(null, posts);
}
// Navigate to the next page
pagination.next(fetchPosts);
});
};
这将开始获取最近到最近的帖子,并手动过滤created_time。
这行得通,但是效率非常低,因为例如,如果我们想要获取一年前的帖子,我们必须迭代页面直到那个时候,这将使用大量请求(可能超过 5k/小时这是速率限制)。
有没有更好的方法来进行这个查询?如何通过提供标签和时间范围来获取 Instagram 帖子?
【问题讨论】:
-
您能否只增加
count以一次抓取更多的照片以减少数量 的帖子获取?当然它们会更大,但这样的东西会有用吗? -
@NickZ 我们确实尝试过这样做(我正在调试这是 OP),我们得到的最大值是 33 个项目/请求。所以,
count并没有真正的帮助...... :-( 还有其他想法吗?我很高兴将 50 分奖励给给出好的答案的人。:D -
您是否考虑过使用 MIN_TAG_ID 和 MAX_TAG_ID 快速迭代到目标日期?我可以想象一种方法,它一次只查询一个帖子,以找到恰好在所需日期之前的 MAX_TAG_ID。
-
看到没有引用任何参数,您需要根据响应进行此过滤。抓取数据并丢弃不需要的数据是不可接受的吗?
-
@sbozzie 是的,这可能就是
pagination.next在内部所做的。但这与日期无关(或者是吗?)。如果您发现日期和标签 id 之间存在关系,那就太好了(例如,21 March 2013被转换为标签 id,使用该标签 id 将获取从该日期开始的帖子)。我猜标签 id 只是一个内部 id,但我不确定。
标签: javascript node.js api instagram instagram-api