-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrawler.js
More file actions
60 lines (48 loc) · 1.7 KB
/
crawler.js
File metadata and controls
60 lines (48 loc) · 1.7 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
const axios = require('axios');
const cheerio = require('cheerio');
const fs = require('fs');
const visitedUrls = new Set();
let results = [];
// Load existing results
if (fs.existsSync('results.json')) {
const existingData = JSON.parse(fs.readFileSync('results.json'));
results = existingData;
existingData.forEach(item => visitedUrls.add(item.url));
}
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
async function crawl(url, depth) {
if (depth === 0 || visitedUrls.has(url)) {
return;
}
visitedUrls.add(url);
try {
const { data } = await axios.get(url, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
});
const $ = cheerio.load(data);
const links = [];
$('a').each((index, element) => {
const link = $(element).attr('href');
if (link && link.startsWith('http')) {
links.push(link);
}
});
results.push({ url, links });
console.log(`Crawled: ${url}`);
for (const link of links) {
await delay(1000); // Add a delay of 1 second between requests
await crawl(link, depth - 1);
}
} catch (error) {
console.error('Error fetching the page:', error);
}
}
function saveResults() {
fs.writeFileSync('results.json', JSON.stringify(results, null, 2));
console.log('Results saved to results.json');
}
const startUrl = 'https://www.gktoday.in/daily-current-affairs-quiz-september-22-23-2024/';
const maxDepth = 2;
crawl(startUrl, maxDepth).then(saveResults);