-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrawler.js
More file actions
48 lines (40 loc) · 1.47 KB
/
crawler.js
File metadata and controls
48 lines (40 loc) · 1.47 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
const axios = require('axios');
const cheerio = require('cheerio');
const { URL } = require('url');
const MAX_DEPTH = 2; // Maximum depth of recursion
const visitedUrls = new Set();
async function crawl(url, depth = 0) {
if (depth > MAX_DEPTH || visitedUrls.has(url)) {
return;
}
try {
const response = await axios.get(url);
const $ = cheerio.load(response.data);
// Extracting links from the page
const links = [];
$('a').each((index, element) => {
const link = $(element).attr('href');
if (link && !link.startsWith('#')) {
links.push(link);
}
});
console.log(`Links found on ${url}:`, links);
// Add the current URL to the set of visited URLs
visitedUrls.add(url);
// Recursively crawl the links found on the page
for (const link of links) {
try {
const absoluteUrl = new URL(link, url).href;
if (absoluteUrl.startsWith('https://en.wikipedia.org') && !visitedUrls.has(absoluteUrl)) {
await crawl(absoluteUrl, depth + 1);
}
} catch (error) {
console.error('Error processing link:', link);
}
}
} catch (error) {
console.error('Error fetching URL:', url);
}
}
// Replace 'https://en.wikipedia.org/wiki/Main_Page' with the URL you want to crawl
crawl('https://en.wikipedia.org/wiki/Main_Page');