网页,使用 Playwright
仅在 Node.js 上可用。
本示例介绍如何使用 Playwright 从网页加载数据。将为每个网页创建一个文档。
Playwright 是一个 Node.js 库,提供了一个高级 API,用于控制多个浏览器引擎,包括 Chromium、Firefox 和 WebKit。您可以使用 Playwright 自动化网页交互,包括从需要 JavaScript 渲染的动态网页中提取数据。
如果您想要更轻量级的解决方案,并且您要加载的网页不需要 JavaScript 渲染,则可以使用 CheerioWebBaseLoader
代替。
安装
- npm
- Yarn
- pnpm
npm install @langchain/community @langchain/core playwright
yarn add @langchain/community @langchain/core playwright
pnpm add @langchain/community @langchain/core playwright
使用方法
import { PlaywrightWebBaseLoader } from "@langchain/community/document_loaders/web/playwright";
/**
* Loader uses `page.content()`
* as default evaluate function
**/
const loader = new PlaywrightWebBaseLoader("https://www.tabnews.com.br/");
const docs = await loader.load();
选项
以下是您可以使用 PlaywrightWebBaseLoaderOptions 接口传递给 PlaywrightWebBaseLoader 构造函数的参数的说明
type PlaywrightWebBaseLoaderOptions = {
launchOptions?: LaunchOptions;
gotoOptions?: PlaywrightGotoOptions;
evaluate?: PlaywrightEvaluate;
};
launchOptions
:一个可选对象,用于指定传递给 playwright.chromium.launch() 方法的其他选项。这可以包括诸如 headless 标志之类的选项,以在无头模式下启动浏览器。gotoOptions
:一个可选对象,用于指定传递给 page.goto() 方法的其他选项。这可以包括诸如 timeout 选项之类的选项,以指定以毫秒为单位的最大导航时间,或 waitUntil 选项以指定何时将导航视为成功。evaluate
:一个可选函数,可用于使用自定义评估函数评估页面上的 JavaScript 代码。这对于从页面提取数据、与页面元素交互或处理特定的 HTTP 响应非常有用。该函数应返回一个 Promise,该 Promise 解析为包含评估结果的字符串。
通过将这些选项传递给 PlaywrightWebBaseLoader
构造函数,您可以自定义加载器的行为,并使用 Playwright 的强大功能来抓取网页并与之交互。
这是一个执行此操作的基本示例
import {
PlaywrightWebBaseLoader,
Page,
Browser,
} from "@langchain/community/document_loaders/web/playwright";
const url = "https://www.tabnews.com.br/";
const loader = new PlaywrightWebBaseLoader(url);
const docs = await loader.load();
// raw HTML page content
const extractedContents = docs[0].pageContent;
以及一个更高级的示例
import {
PlaywrightWebBaseLoader,
Page,
Browser,
} from "@langchain/community/document_loaders/web/playwright";
const loader = new PlaywrightWebBaseLoader("https://www.tabnews.com.br/", {
launchOptions: {
headless: true,
},
gotoOptions: {
waitUntil: "domcontentloaded",
},
/** Pass custom evaluate, in this case you get page and browser instances */
async evaluate(page: Page, browser: Browser, response: Response | null) {
await page.waitForResponse("https://www.tabnews.com.br/va/view");
const result = await page.evaluate(() => document.body.innerHTML);
return result;
},
});
const docs = await loader.load();