发布于 2026-01-06 0 阅读
0

🗄️ 使用 Javascript(在 Node.js 中)抓取网站的最简单方法

🗄️ 使用 Javascript(在 Node.js 中)抓取网站的最简单方法

使用 Puppeteer 抓取网页内容非常简单优雅。让我们尝试抓取Codesnacks 网站,并获取页面上所有包含锚文本和链接的链接。

我们可以使用 Puppeteer 轻松实现这一点。无需先获取数据并进行解析。只需让 Puppeteer 访问页面并在页面上下文中运行您自己的 JavaScript 代码即可。最佳方法是先在浏览器控制台中运行代码,确认一切正常后再将其复制到代码中。

// npm i puppeteer
const puppeteer = require("puppeteer");

// we're using async/await - so we need an async function, that we can run
const run = async () => {
  // open the browser and prepare a page
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  // open the page to scrape
  await page.goto("https://codesnacks.net");

  // execute the JS in the context of the page to get all the links
  const links = await page.evaluate(() => 
    // let's just get all links and create an array from the resulting NodeList
     Array.from(document.querySelectorAll("a")).map(anchor => [anchor.href, anchor.textContent])
  );

  // output all the links
  console.log(links);

  // close the browser 
  await browser.close();
};

// run the async function
run();
Enter fullscreen mode Exit fullscreen mode

在木偶师出现之前,需要将几种工具缝合在一起。

  • 用于获取文档的库(例如 axios 或 node-fetch)
  • 一个用于解析 HTML 并访问 DOM 节点(例如 cheerio)的解析器

这种方法的缺点在于,动态渲染的页面更难抓取。而 Puppeteer 则不存在这个问题,因为它实际上使用的是 Chrome 浏览器——只是没有浏览器头而已。

文章来源:https://dev.to/benjaminmock/the-easiest-way-to-scrape-a-website-with-javascript-in-node-js-54f1