首頁 > web前端 > js教程 > 主體

網頁抓取變得簡單:使用 Puppeteer 解析任何 HTML 頁面

WBOY
發布: 2024-09-05 22:34:41
原創
885 人瀏覽過

Web Scraping Made Easy: Parse Any HTML Page with Puppeteer

想像一下建立一個電子商務平台,我們可以輕鬆地從 eBay、Amazon 和 Flipkart 等主要商店即時取得產品資料。當然,有 Shopify 和類似的服務,但說實話 - 僅為一個項目購買訂閱可能會感覺有點麻煩。所以,我想,為什麼不抓取這些網站並將產品直接儲存在我們的資料庫中呢?這將是為我們的電子商務項目獲取產品的一種高效且具有成本效益的方式。

什麼是網頁抓取?

網頁抓取涉及透過解析網頁的 HTML 來讀取和收集內容,從而從網站中提取資料。它通常涉及自動化瀏覽器或向網站發送 HTTP 請求,然後分析 HTML 結構以檢索特定的資訊片段,如文字、連結或圖像。 Puppeteer 是一個用來抓取網站的函式庫。

?什麼是木偶師?

Puppeteer 是一個 Node.js 函式庫。它提供了一個高級 API,用於控制無頭 Chrome 或 Chromium 瀏覽器。無頭 Chrome 是一個無需 UI 即可運行所有內容的 Chrome 版本(非常適合在背景運行)。

我們可以使用 puppeteer 自動執行各種任務,例如:

  • 網頁抓取:從網站提取內容涉及與頁面的 HTML 和 JavaScript 進行互動。我們通常透過定位 CSS 選擇器來檢索內容。
  • PDF 產生:當您想要直接從網頁產生 PDF,而不是截取螢幕截圖然後將螢幕截圖轉換為 PDF 時,以程式設計方式將網頁轉換為 PDF 是理想的選擇。 (P.S. 如果您已經有解決方法,我們深表歉意)。
  • 自動化測試:透過模擬使用者操作(如點擊按鈕、填寫表單和截圖)在網頁上執行測試。這消除了手動檢查長表格以確保一切就位的繁瑣過程。

?如何開始使用木偶?

首先我們必須安裝函式庫,繼續執行此操作。
使用 npm:

npm i puppeteer # Downloads compatible Chrome during installation.
npm i puppeteer-core # Alternatively, install as a library, without downloading Chrome.
登入後複製

使用紗線:

yarn add puppeteer // Downloads compatible Chrome during installation.
yarn add puppeteer-core // Alternatively, install as a library, without downloading Chrome.
登入後複製

使用 pnpm:

pnpm add puppeteer # Downloads compatible Chrome during installation.
pnpm add puppeteer-core # Alternatively, install as a library, without downloading Chrome.
登入後複製

?示範 puppeteer 使用的範例

這是如何抓取網站的範例。 (P.S. 我使用此程式碼從 Myntra 網站檢索我的電子商務專案的產品。)

const puppeteer = require("puppeteer");
const CategorySchema = require("./models/Category");

// Define the scrape function as a named async function
const scrape = async () => {
    // Launch a new browser instance
    const browser = await puppeteer.launch({ headless: false });

    // Open a new page
    const page = await browser.newPage();

    // Navigate to the target URL and wait until the DOM is fully loaded
    await page.goto('https://www.myntra.com/mens-sport-wear?rawQuery=mens%20sport%20wear', { waitUntil: 'domcontentloaded' });

    // Wait for additional time to ensure all content is loaded
    await new Promise((resolve) => setTimeout(resolve, 25000));

    // Extract product details from the page
    const items = await page.evaluate(() => {
        // Select all product elements
        const elements = document.querySelectorAll('.product-base');
        const elementsArray = Array.from(elements);

        // Map each element to an object with the desired properties
        const results = elementsArray.map((element) => {
            const image = element.querySelector(".product-imageSliderContainer img")?.getAttribute("src");
            return {
                image: image ?? null,
                brand: element.querySelector(".product-brand")?.textContent,
                title: element.querySelector(".product-product")?.textContent,
                discountPrice: element.querySelector(".product-price .product-discountedPrice")?.textContent,
                actualPrice: element.querySelector(".product-price .product-strike")?.textContent,
                discountPercentage: element.querySelector(".product-price .product-discountPercentage")?.textContent?.split(' ')[0]?.slice(1, -1),
                total: 20, // Placeholder value, adjust as needed
                available: 10, // Placeholder value, adjust as needed
                ratings: Math.round((Math.random() * 5) * 10) / 10 // Random rating for demonstration
            };
        });

        return results; // Return the list of product details
    });

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

    // Prepare the data for saving
    const data = {
        category: "mens-sport-wear",
        subcategory: "Mens",
        list: items
    };

    // Create a new Category document and save it to the database
    // Since we want to store product information in our e-commerce store, we use a schema and save it to the database.
    // If you don't need to save the data, you can omit this step.
    const category = new CategorySchema(data);
    console.log(category);
    await category.save();

    // Return the scraped items
    return items;
};

// Export the scrape function as the default export
module.exports = scrape;

登入後複製

?說明:

  • 在此程式碼中,我們使用 Puppeteer 從網站上抓取產品資料。提取詳細資訊後,我們會建立一個架構 (CategorySchema) 來建構這些資料並將其儲存到資料庫中。如果我們想將抓取的產品整合到我們的電子商務商店中,此步驟特別有用。如果不需要將資料儲存在資料庫中,可以省略 schema 相關的程式碼。
  • 在抓取之前,了解頁面的 HTML 結構並確定哪些 CSS 選擇器包含您要提取的內容非常重要。
  • 就我而言,我使用了 Myntra 網站上標識的相關 CSS 選擇器來提取我的目標內容。

以上是網頁抓取變得簡單:使用 Puppeteer 解析任何 HTML 頁面的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!