首页 > web前端 > js教程 > 正文

用 puppeteer 抓取网络!

WBOY
发布: 2024-08-29 11:06:52
原创
771 人浏览过

Scrape the web with puppeteer!

木偶师完整指南 pt.1

Puppeteer:Web 自动化的强大工具

在当今快节奏的 Web 开发环境中,自动化是关键,这就是 Puppeteer 的用武之地。Puppeteer 由 Google 开发,是一个功能强大的 Node.js 库,允许开发人员使用 JavaScript 控制 Chrome 浏览器。无论您是在无头模式下浏览网络以提高效率,还是在完整的浏览器中获得视觉反馈,Puppeteer 都可以让您比以往更轻松地自动执行网页抓取、测试等任务。有了 Puppeteer,曾经需要手动完成的工作现在只需一个脚本即可完成。

为什么要进行网页抓取?

在最近的一个项目中,我与一位客户合作,他的外汇交易社区需要一个登陆页面。他想要类似于您在 MarketWatch 或雅虎财经上看到的股票行情的东西,但他想要的不是股票,而是在网站上显示 1 美元的实时货币兑换率。

虽然有可用的 API 可以提供数据(具有使用限制和月费),但我看到了使用 Puppeteer 创建自定义解决方案的机会。通过预先投入一些时间,我能够免费抓取和显示数据,最终为我的客户节省了经常性费用。

客户网站:Majesticpips.com

设置 puppeteer 变得简单

在我们开始抓取网络以实现其所有荣耀之前,我们必须将 puppeteer 安装到我们的应用程序中。

正如文档中所述

步骤1

使用您选择的 npm、yarn 或 pnpm 安装库。

  • npm 我木偶师

  • 纱线添加木偶师

  • pnpm 添加木偶师

这将在安装过程中下载 Chrome 的兼容版本,这对于初学者来说更容易快速启动和运行。

如果您是一位经验丰富的开发人员并且有您想要使用的特定 chrome/chromium 版本;然后安装这些软件包

  • npm i puppeteer-core

  • 纱线添加 puppeteer-core

  • pnpm 添加 puppeteer-core

最适合您,该软件包将是轻量级的,因为它只安装 puppeteer,而 chrome 版本则由您决定。

安装“puppeteer”对于初次测试者来说是更好的选择。它简化了设置并确保您拥有 Chromium 的工作版本,让您可以专注于编写脚本。

步骤2

现在在您的 JS 文件中,您需要为使用 ES 模块系统(ES6 标准)且节点版本为 12 及更高版本的应用程序导入 puppeteer。

从“puppeteer”导入puppeteer; (推荐)

从 'puppeteer-core' 导入 puppeteer;

或者您可以使用 Node.js 的 commonJs 模块系统的 require 语法,该语法也与旧版本的 Node.js 兼容。

const puppeteer = require('puppeteer');

const puppeteer = require('puppeteer-core');

步骤3

导入Puppeteer后,我们就可以开始编写执行网页抓取的命令了。下面的代码显示了您需要使用的内容。

我们使用库提供的这些方法启动浏览器。

const browser = await puppeteer.launch();

const page = await browser.newPage();

await browser.close();
登录后复制

puppeteer.launch() = 此方法启动一个新的浏览器实例。

browser.newPage() = 此方法在浏览器实例中创建一个新页面(或选项卡)。

browser.close() = 此方法关闭浏览器实例。

在 puppeteer.launch() 中,我们可以传递参数来根据我们的喜好自定义浏览器启动。我们将在第 2 部分中更详细地介绍这一点。但是,默认情况下,puppeteer.launch() 具有预设值,例如将无头模式设置为 true。

步骤4

浏览器已经启动,现在我们已经有了一个可以上网的页面了。让我们导航到我们将抓取一些数据的网站。

在此示例中,我们将从 qoutes 网站抓取数据。

 await page.goto(https://quotes.toscrape.com/)

 await page.screenshot({ path: 'screenshot.png' })
登录后复制

我添加了await page.screenshot({ path: 'screenshot.png' }) 到其中。这是一个很好的工具,可以确保一切按计划进行。执行此代码时,您的项目目录中将有一个图像文件,用于捕获您正在抓取的网站的当前状态。您还可以根据自己的喜好调整文件名。

如果一切正常,则继续执行步骤 5。

步骤5

现在我们的脚本已经成型,让我们深入研究从网页提取数据的关键部分。这是我们的脚本目前的样子:

const puppeteer = require('puppeteer');

(async () => {

const browser = await puppeteer.launch();

const page = await browser.newPage();

await page.goto(https://quotes.toscrape.com/)

await page.screenshot({ path: 'screenshot.png' })

 const quotesScraper = await page.evaluate(() => {

const quotes = document.querySelectorAll(".quote"); 
    const quotesArray = [];

   for (const quote of quotes) { 
       const texts = quote.querySelector(".text").innerText; 
         const author = quote.querySelector(".author").innerText;  

        quotesArray.push({
           quote: texts,
           author
         });

     }
     return quotesArray;
});

console.log(quotesScraper);

await browser.close();

})();
登录后复制

要验证数据是否已成功抓取,我们可以在 CLI 中运行节点“server-file-name”,数据将使用 console.log(quotesScraper); 显示在控制台中。

[
  {
    quote: '“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”',
    author: 'Albert Einstein'
  },
  {
    quote: '“It is our choices, Harry, that show what we truly are, far more than our abilities.”',
    author: 'J.K. Rowling'
  },
  {
    quote: '“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”',
    author: 'Albert Einstein'
  },
  {
    quote: '“The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.”',
    author: 'Jane Austen'
  },
  {
    quote: "“Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.”",
    author: 'Marilyn Monroe'
  }
....
]
登录后复制

await page.evaluate(() => { ... }): This is where the magic happens. The evaluate method allows us to run JavaScript code within the context of the page we're scraping. It's as if you're opening the browser's developer console and running the code directly on the page.

const quotes = document.querySelectorAll(".quote");: Here, we're selecting all elements on the page that match the .quote class. This gives us a NodeList of quote elements.

const quotesArray = [];: We initialize an empty array to store the quotes we extract.

for (const quote of quotes) { ... }: This loop iterates over each quote element. For each one, we extract the text of the quote and the author.

quotesArray.push({ quote: texts, author });: For each quote, we create an object containing the quote text and the author, then push this object into the quotesArray.

return quotesArray;: Finally, we return the array of quotes, which is then stored in quotesScraper in our Node.js environment.

This method of extracting data is powerful because it allows you to interact with the page just like a user would, but in an automated and programmatic way.

Closing the Browser

await browser.close();: After scraping the data, it's important to close the browser to free up resources. This line ensures that the browser instance we launched is properly shut down.

Looking Ahead to Part 2

With this script, you've successfully scraped data from a website using Puppeteer. But we're just scratching the surface of what's possible. In Part 2, we’ll explore more advanced techniques like handling dynamic content and use Express.JS to create API functionality of scrapped data. Stay tuned as we delve deeper into the world of Puppeteer!

以上是用 puppeteer 抓取网络!的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!