-
Notifications
You must be signed in to change notification settings - Fork 0
/
crawl.js
90 lines (73 loc) · 2.66 KB
/
crawl.js
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
const {JSDOM} = require('jsdom')
async function crawlPage(baseURL, current_url, pages) {
console.log(`crawling ${current_url}`)
const base_url_object = new URL(baseURL)
const current_url_object = new URL(current_url)
if (base_url_object.hostname !== current_url_object.hostname){
return pages
}
const normalized_current_url = normalizeURL(current_url)
if (pages[normalized_current_url] > 0) {
pages[normalized_current_url]++
return pages
}
pages[normalized_current_url] = 1
// console.log(await response.text())
try {
const response = await fetch(current_url)
if (response.status > 399) {
console.log(`error, status code: ${response.status}`)
return pages
}
const contentType = response.headers.get("content-type")
if (!contentType.includes("text/html")) {
console.log(`non html response on page ${current_url}. content type ${contentType}`)
return pages
}
const html_body = await response.text()
const next_urls = getURLfromHTMLcode(html_body, baseURL)
for (const next_url of next_urls) {
pages = await crawlPage(baseURL, next_url, pages)
}
}
catch (error) {
console.log(`error ${error.message} on the page: ${current_url}`)
}
return pages
}
function normalizeURL(url) {
const url_object = new URL(url)
const hostname_path = `${url_object.hostname}${url_object.pathname}`
if (hostname_path.length > 0 && hostname_path.slice(-1) === '/') {
return hostname_path.slice(0, -1) // everything except the last character
}
return hostname_path
}
function getURLfromHTMLcode(htmlCode, baseURL) {
const urls = []
const dom = new JSDOM(htmlCode)
const links = dom.window.document.querySelectorAll('a')
for (const link of links) {
if (link.href.slice(0, 1) == '/') { // relative url
try {
const url_object = new URL(`${baseURL}${link.href}`) // create errors if sth wrong
urls.push(url_object.href)
} catch (error) { // error is an object
console.log(`error. something wrong with the url: ${error.message}`)
}
} else { // absolute url
try {
const url_object = new URL(link.href) // create errors if something wrong
urls.push(url_object.href)
} catch (error) { // an object
console.log(`error. something wrong with the url: ${error.message}`)
}
}
}
return urls
}
module.exports = {
normalizeURL,
getURLfromHTMLcode,
crawlPage,
}