-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscrape.js
More file actions
96 lines (78 loc) · 2.05 KB
/
Copy pathscrape.js
File metadata and controls
96 lines (78 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const cheerio = require('cheerio');
const fs = require('fs-extra');
const get = require('lodash/get');
const request = require('request');
const download = require(`./utils/download-file`);
const username = process.argv[2];
if (!username) {
console.log(
`
You didn't supply an Instagram username!
Run this command like:
node scrape.js INSTAGRAM_USERNAME
`
);
process.exit();
}
const posts = [];
const bail = (err) => {
console.error(err);
process.exit(0);
return false;
};
const toISO8601 = (timestamp) => new Date(timestamp * 1000).toJSON();
const saveJSON = () =>
fs.writeFileSync(`./data/instagramPosts.json`, JSON.stringify(posts, ``, 2));
fs.ensureDirSync('./data/images');
const getPosts = () => {
const url = `https://www.instagram.com/${username}/`;
request(url, function (err, response, body) {
if (err) return bail(err);
const $ = cheerio.load(body);
let obj;
try {
let data = $('script:not([src])')
.filter((i, el) => /^window._sharedData\s+\=/.test(el.children[0].data))
.get(0)
.children[0].data.match(/\{(.|[\r\n])*\}/g);
obj = JSON.parse(data[0]);
} catch (err) {
return bail(err);
}
const edges = get(
obj,
'entry_data.ProfilePage[0].graphql.user.edge_owner_to_timeline_media.edges',
[]
);
const images = edges
.map(
({
node: {
id,
shortcode,
dimensions,
display_url,
taken_at_timestamp,
...node
},
}) =>
node.isVideo
? null
: {
id,
shortcode,
time: toISO8601(taken_at_timestamp),
url: `https://www.instagram.com/p/${shortcode}`,
media: display_url,
image: `images/${shortcode}.jpg`,
}
)
.forEach((item) => {
if (!item) return;
download(item.media, `./data/images/${item.shortcode}.jpg`);
posts.push(item);
});
saveJSON();
});
};
getPosts();