-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscrape.js
More file actions
111 lines (95 loc) · 2.58 KB
/
scrape.js
File metadata and controls
111 lines (95 loc) · 2.58 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
const {fetch} = require('cross-fetch');
const {fs} = require('fs')
const url = 'https://graphql.anilist.co';
const perPage = 50; // Number of characters per page
let page = 1; // Initial page number
let hasNextPage = true; // Flag to determine if there are more pages
async function fetchCharacters() {
const characters = [];
while (hasNextPage) {
const variables = {
page: page,
perPage: perPage,
};
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query: `
query ($page: Int, $perPage: Int) {
Page(page: $page, perPage: $perPage) {
pageInfo {
total
currentPage
lastPage
hasNextPage
}
characters {
id
name {
first
last
}
gender
age
media {
nodes {
title {
romaji
}
}
}
}
}
}
`,
variables: variables,
}),
};
const response = await fetch(url, options);
const { data, errors } = await response.json();
if (errors) {
console.error(errors);
break; // Stop fetching in case of errors
}
const { Page } = data;
const { pageInfo, characters: fetchedCharacters } = Page;
// Process the fetched characters
fetchedCharacters.forEach((character) => {
const { name, gender, age, media } = character;
const animeName = media.nodes.length > 0 ? media.nodes[0].title.romaji : null;
characters.push({
name: `${name.first} ${name.last}`,
gender,
age,
animeName,
});
});
hasNextPage = pageInfo.hasNextPage;
page++;
console.log(`Received data for page ${page - 1}`);
}
return characters;
}
async function saveCharactersToJson(characters) {
const jsonData = JSON.stringify(characters, null, 2);
fs.writeFile('characters.json', jsonData, (err) => {
if (err) {
console.error('Error saving characters to JSON:', err);
} else {
console.log('Characters saved to characters.json');
}
});
}
async function main() {
try {
const characters = await fetchCharacters();
await saveCharactersToJson(characters);
} catch (error) {
console.error('Error retrieving characters:', error);
}
}
main();