首頁  >  文章  >  web前端  >  用 puppeteer 抓取網路!

用 puppeteer 抓取網路!

WBOY
WBOY原創
2024-08-29 11:06:52776瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn