"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > 손쉬운 웹 스크래핑: Puppeteer를 사용하여 모든 HTML 페이지 구문 분석

손쉬운 웹 스크래핑: Puppeteer를 사용하여 모든 HTML 페이지 구문 분석

2024-11-05에 게시됨
검색:489

Web Scraping Made Easy: Parse Any HTML Page with Puppeteer

eBay, Amazon, Flipkart와 같은 주요 매장에서 제품 데이터를 실시간으로 쉽게 가져올 수 있는 전자상거래 플랫폼을 구축한다고 상상해 보세요. 물론, Shopify 및 유사한 서비스가 있지만 솔직하게 말하면 프로젝트에 대해서만 구독을 구매하는 것이 약간 번거로울 수 있습니다. 그래서 저는 이러한 사이트를 긁어내고 제품을 우리 데이터베이스에 직접 저장해 보는 것은 어떨까라고 생각했습니다. 이는 전자상거래 프로젝트에 필요한 제품을 얻는 효율적이고 비용 효과적인 방법이 될 것입니다.

웹 스크래핑이란 무엇입니까?

웹 스크래핑에는 콘텐츠를 읽고 수집하기 위해 웹페이지의 HTML을 구문 분석하여 웹사이트에서 데이터를 추출하는 작업이 포함됩니다. 여기에는 브라우저를 자동화하거나 사이트에 HTTP 요청을 보낸 다음 HTML 구조를 분석하여 텍스트, 링크 또는 이미지와 같은 특정 정보를 검색하는 작업이 포함되는 경우가 많습니다. Puppeteer는 웹사이트를 스크랩하는 데 사용되는 라이브러리 중 하나입니다.

?인형술사란 무엇인가요?

Puppeteer는 Node.js 라이브러리입니다. 헤드리스 Chrome 또는 Chromium 브라우저를 제어하기 위한 고급 API를 제공합니다. 헤드리스 Chrome은 UI 없이 모든 것을 실행하는 Chrome 버전입니다(백그라운드에서 실행하기에 적합).

Puppeteer를 사용하여 다음과 같은 다양한 작업을 자동화할 수 있습니다.

  • 웹 스크래핑: 웹사이트에서 콘텐츠를 추출하려면 페이지의 HTML 및 JavaScript와 상호작용해야 합니다. 일반적으로 CSS 선택기를 타겟팅하여 콘텐츠를 검색합니다.
  • PDF 생성: 스크린샷을 찍은 다음 스크린샷을 PDF로 변환하는 대신 웹 페이지에서 PDF를 직접 생성하려는 경우 프로그래밍 방식으로 웹 페이지를 PDF로 변환하는 것이 이상적입니다. (추신: 이미 이에 대한 해결 방법이 있다면 사과드립니다.)
  • 자동 테스트: 버튼 클릭, 양식 작성, 스크린샷 찍기와 같은 사용자 작업을 시뮬레이션하여 웹페이지에서 테스트를 실행합니다. 이렇게 하면 모든 것이 제자리에 있는지 확인하기 위해 긴 양식을 수동으로 처리하는 지루한 프로세스가 제거됩니다.

?인형극을 시작하는 방법은 무엇입니까?

먼저 라이브러리를 설치해야 합니다. 계속해서 이 작업을 수행하세요.
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.

? 인형극의 사용을 보여주는 예

다음은 웹사이트를 스크래핑하는 방법의 예입니다. (추신: 저는 이 코드를 사용하여 전자상거래 프로젝트를 위해 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 sport wear', { 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)를 생성하여 이 데이터를 데이터베이스에 구성하고 저장합니다. 이 단계는 스크랩한 제품을 전자상거래 상점에 통합하려는 경우 특히 유용합니다. 데이터베이스에 데이터를 저장할 필요가 없는 경우 스키마 관련 코드를 생략할 수 있습니다.
  • 스크래핑하기 전에 페이지의 HTML 구조를 이해하고 추출하려는 콘텐츠가 포함된 CSS 선택기를 식별하는 것이 중요합니다.
  • 저의 경우 Myntra 웹사이트에서 식별된 관련 CSS 선택기를 사용하여 제가 타겟팅한 콘텐츠를 추출했습니다.
릴리스 선언문 이 기사는 https://dev.to/niharikaa/web-scraping-made-easy-parse-any-html-page-with-puppeteer-3dk8?1에 복제되어 있습니다. 침해가 있는 경우에는 Study_golang@163으로 문의하시기 바랍니다. .com에서 삭제하세요
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3