跳到主要内容
兼容性仅在 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";

/**
 * 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;
};
  1. launchOptions:一个可选对象,用于指定传递给 playwright.chromium.launch() 方法的附加选项。这可以包括诸如无头模式标志之类的选项,用于在无头模式下启动浏览器。
  2. gotoOptions:一个可选对象,用于指定传递给 page.goto() 方法的附加选项。这可以包括诸如 timeout 选项之类的选项,用于指定最大导航时间(以毫秒为单位),或 waitUntil 选项,用于指定何时将导航视为成功。
  3. evaluate:一个可选函数,可用于使用自定义评估函数在页面上评估 JavaScript 代码。这对于从页面提取数据、与页面元素交互或处理特定的 HTTP 响应非常有用。该函数应返回一个解析为包含评估结果的字符串的 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();

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.