-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add web crawler and publish new version
- Loading branch information
Showing
5 changed files
with
224 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import fetch from 'node-fetch'; | ||
import * as cheerio from 'cheerio'; | ||
|
||
export interface ItemDetailsConfig { | ||
key: string; | ||
selector: string; | ||
attribute?: string; | ||
} | ||
|
||
export interface CrawlerConfig { | ||
url?: string; | ||
html?: string; | ||
itemSelector: string; | ||
itemDetails: ItemDetailsConfig[]; | ||
} | ||
|
||
export const WebCrawl = async (config: CrawlerConfig) => { | ||
const { url, itemSelector, itemDetails } = config; | ||
let { html } = config; | ||
|
||
if (url) { | ||
const data = await fetch(url); | ||
html = await data.text(); | ||
} else if (!html) { | ||
console.error('Please specify either "html" or "url" in config'); | ||
return []; | ||
} | ||
|
||
const $ = cheerio.load(html); | ||
const formattedData = []; | ||
|
||
$(itemSelector).each((i: number, item: any) => { | ||
const itemData = {}; | ||
|
||
itemDetails.forEach(option => { | ||
let detailsElement = $(item).find(option.selector); | ||
|
||
if (option.attribute) { | ||
detailsElement = detailsElement?.attr(option.attribute) ?? ''; | ||
} else { | ||
detailsElement = detailsElement?.text() ?? ''; | ||
} | ||
|
||
itemData[option.key] = detailsElement.trim(); | ||
}); | ||
|
||
formattedData.push(itemData); | ||
}); | ||
|
||
return formattedData; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters