Skip to main content
兼容性仅在 Node.js 上可用。
此示例介绍如何使用 Playwright 从网页加载数据。每个网页将创建一个文档。 Playwright 是一个 Node.js 库,提供高级 API 来控制多个浏览器引擎,包括 Chromium、Firefox 和 WebKit。您可以使用 Playwright 自动化网页交互,包括从需要 JavaScript 渲染的动态网页中提取数据。 如果您想要更轻量级的解决方案,并且您要加载的网页不需要 JavaScript 渲染,可以使用 CheerioWebBaseLoader 代替。

设置

npm
npm install @langchain/community @langchain/core playwright

用法

import { PlaywrightWebBaseLoader } from "@langchain/community/document_loaders/web/playwright";

/**
 * 加载器默认使用 `page.content()`
 * 作为评估函数
 **/
const loader = new PlaywrightWebBaseLoader("https://www.tabnews.com.br/");

const docs = await loader.load();

选项

以下是您可以使用 PlaywrightWebBaseLoaderOptions 接口传递给 PlaywrightWebBaseLoader 构造函数的参数说明:
type PlaywrightWebBaseLoaderOptions = {
  launchOptions?: LaunchOptions;
  gotoOptions?: PlaywrightGotoOptions;
  evaluate?: PlaywrightEvaluate;
};
  1. launchOptions:一个可选对象,指定要传递给 playwright.chromium.launch() 方法的附加选项。这可以包括诸如 headless 标志以无头模式启动浏览器等选项。
  2. gotoOptions:一个可选对象,指定要传递给 page.goto() 方法的附加选项。这可以包括诸如 timeout 选项以指定最大导航时间(毫秒),或 waitUntil 选项以指定何时考虑导航成功。
  3. 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();

// 原始 HTML 页面内容
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",
  },
  /** 传递自定义评估函数,在此情况下您将获得页面和浏览器实例 */
  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();