想像一下建立一個電子商務平台,我們可以輕鬆地從 eBay、Amazon 和 Flipkart 等主要商店即時取得產品資料。當然,有 Shopify 和類似的服務,但說實話 - 僅為一個項目購買訂閱可能會感覺有點麻煩。所以,我想,為什麼不抓取這些網站並將產品直接儲存在我們的資料庫中呢?這將是為我們的電子商務項目獲取產品的一種高效且具有成本效益的方式。
網頁抓取涉及透過解析網頁的 HTML 來讀取和收集內容,從而從網站中提取資料。它通常涉及自動化瀏覽器或向網站發送 HTTP 請求,然後分析 HTML 結構以檢索特定的資訊片段,如文字、連結或圖像。 Puppeteer 是一個用來抓取網站的函式庫。
Puppeteer 是一個 Node.js 函式庫。它提供了一個高級 API,用於控制無頭 Chrome 或 Chromium 瀏覽器。無頭 Chrome 是一個無需 UI 即可運行所有內容的 Chrome 版本(非常適合在背景運行)。
我們可以使用 puppeteer 自動執行各種任務,例如:
首先我們必須安裝函式庫,繼續執行此操作。
使用 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.
這是如何抓取網站的範例。 (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 解析任何 HTML 頁面的詳細內容。更多資訊請關注PHP中文網其他相關文章!