39 lines
1.4 KiB
JavaScript
39 lines
1.4 KiB
JavaScript
|
|
const axios = require('axios');
|
||
|
|
const cheerio = require('cheerio');
|
||
|
|
|
||
|
|
const getLatestPost = async (username) => {
|
||
|
|
try {
|
||
|
|
// Fetch the Instagram page
|
||
|
|
const response = await axios.get(`https://www.instagram.com/${username}/`);
|
||
|
|
const html = response.data;
|
||
|
|
|
||
|
|
// Load the HTML into cheerio
|
||
|
|
const $ = cheerio.load(html);
|
||
|
|
|
||
|
|
|
||
|
|
// Extract the script tag containing the JSON data
|
||
|
|
const scriptTag = $('script[type="text/javascript"]').get().find(script => script.children[0].data.includes('window._sharedData'));
|
||
|
|
console.log(scriptTag);
|
||
|
|
const jsonData = scriptTag.children[0].data.split(' = ')[1].slice(0, -1);
|
||
|
|
const data = JSON.parse(jsonData);
|
||
|
|
|
||
|
|
// Get the latest post
|
||
|
|
const latestPost = data.entry_data.ProfilePage[0].graphql.user.edge_owner_to_timeline_media.edges[0].node;
|
||
|
|
|
||
|
|
// Extract relevant information
|
||
|
|
const postDetails = {
|
||
|
|
id: latestPost.id,
|
||
|
|
shortcode: latestPost.shortcode,
|
||
|
|
imageUrl: latestPost.display_url,
|
||
|
|
caption: latestPost.edge_media_to_caption.edges[0]?.node.text || 'No caption',
|
||
|
|
timestamp: latestPost.taken_at_timestamp,
|
||
|
|
};
|
||
|
|
|
||
|
|
console.log(postDetails);
|
||
|
|
} catch (error) {
|
||
|
|
console.error('Error fetching the latest post:', error);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
// Replace 'instagram' with the desired username
|
||
|
|
getLatestPost('instagram');
|