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

Added CSS selector to Cheerio #948

Merged
merged 1 commit into from
Sep 20, 2023
Merged
Changes from all commits
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
24 changes: 21 additions & 3 deletions packages/components/nodes/documentloaders/Cheerio/Cheerio.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { INode, INodeData, INodeParams } from '../../../src/Interface'
import { TextSplitter } from 'langchain/text_splitter'
import { CheerioWebBaseLoader } from 'langchain/document_loaders/web/cheerio'
import { CheerioWebBaseLoader, WebBaseLoaderParams } from 'langchain/document_loaders/web/cheerio'
import { test } from 'linkifyjs'
import { parse } from 'css-what'
import { webCrawl, xmlScrape } from '../../../src'
import { SelectorType } from 'cheerio'

class Cheerio_DocumentLoaders implements INode {
label: string
Expand All @@ -18,7 +20,7 @@ class Cheerio_DocumentLoaders implements INode {
constructor() {
this.label = 'Cheerio Web Scraper'
this.name = 'cheerioWebScraper'
this.version = 1.0
this.version = 1.1
this.type = 'Document'
this.icon = 'cheerio.svg'
this.category = 'Document Loaders'
Expand Down Expand Up @@ -66,6 +68,14 @@ class Cheerio_DocumentLoaders implements INode {
'Only used when "Get Relative Links Method" is selected. Set 0 to retrieve all relative links, default limit is 10.',
warning: `Retrieving all links might take long time, and all links will be upserted again if the flow's state changed (eg: different URL, chunk size, etc)`
},
{
label: 'Selector (CSS)',
name: 'selector',
type: 'string',
description: 'Specify a CSS selector to select the content to be extracted',
optional: true,
additionalParams: true
},
{
label: 'Metadata',
name: 'metadata',
Expand All @@ -88,10 +98,18 @@ class Cheerio_DocumentLoaders implements INode {
throw new Error('Invalid URL')
}

const selector: SelectorType = nodeData.inputs?.selector as SelectorType

let params: WebBaseLoaderParams = {}
if (selector) {
parse(selector) // comes with cheerio - will throw error if invalid
params['selector'] = selector
}

async function cheerioLoader(url: string): Promise<any> {
try {
let docs = []
const loader = new CheerioWebBaseLoader(url)
const loader = new CheerioWebBaseLoader(url, params)
if (textSplitter) {
docs = await loader.loadAndSplit(textSplitter)
} else {
Expand Down