Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update crawler.ts: Add hostname check to keep crawler on the same domain. #15

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 26 additions & 11 deletions src/app/api/crawl/crawler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import cheerio from 'cheerio';

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

your linter shouldnt be making changes for this PR

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorting now.

import { NodeHtmlMarkdown } from 'node-html-markdown';
import cheerio from "cheerio";
import { NodeHtmlMarkdown } from "node-html-markdown";

interface Page {
url: string;
Expand All @@ -11,9 +11,12 @@ class Crawler {
private pages: Page[] = [];
private queue: { url: string; depth: number }[] = [];

constructor(private maxDepth = 2, private maxPages = 1) { }
constructor(private maxDepth = 2, private maxPages = 1) {}

async crawl(startUrl: string): Promise<Page[]> {
// Capture the hostname of the start URL
const startHostname = new URL(startUrl).hostname;

// Add the start URL to the queue
this.addToQueue(startUrl);

Expand All @@ -34,8 +37,8 @@ class Crawler {
// Parse the HTML and add the page to the list of crawled pages
this.pages.push({ url, content: this.parseHtml(html) });

// Extract new URLs from the page HTML and add them to the queue
this.addNewUrlsToQueue(this.extractUrls(html, url), depth);
// Pass startHostname to addNewUrlsToQueue
this.addNewUrlsToQueue(this.extractUrls(html, url), depth, startHostname);
}

// Return the list of crawled pages
Expand All @@ -58,8 +61,16 @@ class Crawler {
this.queue.push({ url, depth });
}

private addNewUrlsToQueue(urls: string[], depth: number) {
this.queue.push(...urls.map(url => ({ url, depth: depth + 1 })));
private addNewUrlsToQueue(
urls: string[],
depth: number,
startHostname: string
) {
const filteredUrls = urls.filter((url) => {
const hostname = new URL(url).hostname;
return hostname === startHostname;
});
this.queue.push(...filteredUrls.map((url) => ({ url, depth: depth + 1 })));
}

private async fetchPage(url: string): Promise<string> {
Expand All @@ -68,20 +79,24 @@ class Crawler {
return await response.text();
} catch (error) {
console.error(`Failed to fetch ${url}: ${error}`);
return '';
return "";
}
}

private parseHtml(html: string): string {
const $ = cheerio.load(html);
$('a').removeAttr('href');
$("a").removeAttr("href");
return NodeHtmlMarkdown.translate($.html());
}

private extractUrls(html: string, baseUrl: string): string[] {
const $ = cheerio.load(html);
Copy link

@athrael-soju athrael-soju Oct 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor observation: This will give a 'deprecated' warning. You can do import { load } from 'cheerio'; and use the load by itself instead.

const relativeUrls = $('a').map((_, link) => $(link).attr('href')).get() as string[];
return relativeUrls.map(relativeUrl => new URL(relativeUrl, baseUrl).href);
const relativeUrls = $("a")
.map((_, link) => $(link).attr("href"))
.get() as string[];
return relativeUrls.map(
(relativeUrl) => new URL(relativeUrl, baseUrl).href
);
}
}

Expand Down