Skip to content

Instantly share code, notes, and snippets.

@ipetropolsky
Last active March 12, 2022 20:23
Show Gist options
  • Save ipetropolsky/968240ca76b4a50e1640520ba7c9bd92 to your computer and use it in GitHub Desktop.
Save ipetropolsky/968240ca76b4a50e1640520ba7c9bd92 to your computer and use it in GitHub Desktop.
Instagram photos JSON
/* Запустить на странице https://www.instagram.com/%username%/ */
var promise = new Promise((resolve, reject) => {
const DELAY = 1000;
const DEVATION = 250;
const limit = 50;
// Сколько «страниц» скачать (на каждой по ${limit} фоток), 0 == без ограничений
const totalPages = 0;
// true если аккаунт друга (на кого подписан) или свой, иначе false
const isMyFriendPage = true;
const user = window._sharedData.entry_data.ProfilePage[0].graphql.user;
const hash = isMyFriendPage ? 'f2405b236d85e8296cf30347c9f08c2a' : '9dcf6e1a98bc7f6e92953d5a61027b98';
console.log('🤖 Скачиваем данные об аккаунте ' + user.username);
console.log('☝️ (Общедоступные)');
const result = {
userShort: {
id: user.id,
username: user.username,
url: `https://www.instagram.com/${user.username}/`,
posts: user.edge_owner_to_timeline_media.count,
},
user: user,
edges: [],
};
function makeURL(cursor = '') {
return `https://www.instagram.com/graphql/query/?query_hash=${hash}&variables=${encodeURIComponent(`{"id":"${user.id}","first":${limit},"after":"${cursor}"}`)}`;
}
function getLocation(node) {
const {id, name, slug} = node.location || {};
return node.location ? {
id,
name,
url: `https://www.instagram.com/explore/locations/${id}/${slug}`,
} : null;
}
function getTitle(node) {
const edges = node.edge_media_to_caption.edges;
return edges.length ? edges[0].node.text : null;
}
function getPost(node) {
return {
owner: node.owner.username,
likes: node.edge_media_preview_like.count,
comments: node.edge_media_to_comment.count,
shortcode: node.shortcode,
timestamp: node.taken_at_timestamp,
is_video: node.is_video,
title: getTitle(node),
url: `https://www.instagram.com/p/${node.shortcode}/`,
location: getLocation(node),
resources: node.display_resources.reduce((result, resource) => {
const {src, config_width: width, config_height: height} = resource;
result[width] = {src, width, height};
return result;
}, {}),
};
}
let currentPage = 0;
function fetchPosts(cursor) {
currentPage += 1;
console.log('🤖 Загружаем страницу №' + currentPage + '…');
fetch(makeURL(cursor)).then((response) => response.json()).then(
(response) => {
const media = response.data.user.edge_owner_to_timeline_media;
const currentLength = result.edges.length;
console.log('🤖 Обрабатываем результаты страницы №' + currentPage + '…');
media.edges.forEach((edge) => {
result.edges.push(edge);
console.log('📷 ' + result.edges.length + ' из ' + user.edge_owner_to_timeline_media.count);
});
const stopLoading = currentPage === totalPages;
if (media.page_info.has_next_page && !stopLoading) {
const delay = Math.round(DEVATION * 2 * Math.random() + DELAY - DEVATION);
console.log('🤖 Ждём ' + delay + ' мс');
setTimeout(() => {
fetchPosts(media.page_info.end_cursor);
}, delay);
} else {
console.log('✅ Всё готово!');
console.log('💡 Скопировать результаты: promise.then((result) => { copy(result); });')
resolve(result);
}
},
reject,
);
}
fetchPosts('');
});
/* Запустить на странице https://www.instagram.com/%username%/ */
var promise = new Promise((resolve, reject) => {
const limit = 50;
// Сколько «страниц» скачать (на каждой по ${limit} фоток), 0 == без ограничений
const totalPages = 0;
// true если аккаунт друга (на кого подписан) или свой, иначе false
const isMyFriendPage = true;
const user = window._sharedData.entry_data.ProfilePage[0].graphql.user;
const hash = isMyFriendPage ? 'f2405b236d85e8296cf30347c9f08c2a' : '9dcf6e1a98bc7f6e92953d5a61027b98';
console.log('🤖 Скачиваем данные об аккаунте ' + user.username);
console.log('☝️ (Общедоступные)');
const result = {
user: {
id: user.id,
username: user.username,
url: `https://www.instagram.com/${user.username}/`,
posts: user.edge_owner_to_timeline_media.count,
},
posts: [],
};
function makeURL(cursor = '') {
return `https://www.instagram.com/graphql/query/?query_hash=${hash}&variables=${encodeURIComponent(`{"id":"${user.id}","first":${limit},"after":"${cursor}"}`)}`;
}
function getLocation(node) {
const {id, name, slug} = node.location || {};
return node.location ? {
id,
name,
url: `https://www.instagram.com/explore/locations/${id}/${slug}`,
} : null;
}
function getTitle(node) {
const edges = node.edge_media_to_caption.edges;
return edges.length ? edges[0].node.text : null;
}
function getPost(node) {
return {
owner: node.owner.username,
likes: node.edge_media_preview_like.count,
comments: node.edge_media_to_comment.count,
shortcode: node.shortcode,
timestamp: node.taken_at_timestamp,
is_video: node.is_video,
title: getTitle(node),
url: `https://www.instagram.com/p/${node.shortcode}/`,
location: getLocation(node),
resources: node.display_resources.reduce((result, resource) => {
const {src, config_width: width, config_height: height} = resource;
result[width] = {src, width, height};
return result;
}, {}),
};
}
let currentPage = 0;
function fetchPosts(cursor) {
currentPage += 1;
console.log('🤖 Загружаем страницу №' + currentPage + '…');
fetch(makeURL(cursor)).then((response) => response.json()).then(
(response) => {
const media = response.data.user.edge_owner_to_timeline_media;
const currentLength = result.posts.length;
console.log('🤖 Обрабатываем результаты страницы №' + currentPage + '…');
media.edges.forEach((edge) => {
result.posts.push(getPost(edge.node));
console.log('📷 ' + result.posts.length + ' из ' + (currentLength + media.edges.length));
});
const stopLoading = currentPage === totalPages;
if (media.page_info.has_next_page && !stopLoading) {
fetchPosts(media.page_info.end_cursor);
} else {
console.log('✅ Всё готово!');
console.log('💡 Скопировать результаты: promise.then((result) => { copy(result); });')
resolve(result);
}
},
reject,
);
}
fetchPosts('');
});
/* После скачивания */
// Скопировать JSON
promise.then((result) => {
//console.log(result);
copy(result);
});
// Скопировать JSON с постами, отсортированными по лайкам
promise.then((result) => {
result.posts.sort((a, b) => b.likes - a.likes);
copy(result);
});
// Вывести первые 100 урлов из отсортированного списка
promise.then((result) => {
result.posts.sort((a, b) => b.likes - a.likes);
for (var s = '', i = 0; i < 100; i++) {
s += `${result.posts[i].url}\n`;
}
console.log(s);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment