인형극으로 웹을 긁어보세요!

WBOY
풀어 주다: 2024-08-29 11:06:52
원래의
771명이 탐색했습니다.

Scrape the web with puppeteer!

인형사 전체 가이드 pt.1

Puppeteer: 웹 자동화를 위한 강력한 도구

오늘날 빠르게 변화하는 웹 개발 환경에서는 자동화가 핵심입니다. 바로 여기서 Puppeteer가 등장합니다. Google에서 개발한 Puppeteer는 개발자가 JavaScript를 사용하여 Chrome 브라우저를 제어할 수 있게 해주는 강력한 Node.js 라이브러리입니다. 효율성을 위해 헤드리스 모드에서 웹을 탐색하든, 시각적 피드백을 위해 풀 브라우저에서 웹을 탐색하든, Puppeteer를 사용하면 웹 스크래핑, 테스트 등과 같은 작업을 그 어느 때보다 쉽게 ​​자동화할 수 있습니다. Puppeteer를 사용하면 한때 수동 작업이 필요했던 작업이 이제는 스크립트만으로 가능해졌습니다.

웹 스크래핑을 사용하는 이유는 무엇입니까?

최근 프로젝트에서 저는 외환 거래 커뮤니티를 위한 랜딩 페이지가 필요한 고객과 함께 일했습니다. 그는 MarketWatch 또는 Yahoo Finance에서 볼 수 있는 주식 시세 표시기와 유사한 것을 원했지만 주식 대신 사이트 전체에 미화 1달러에 대한 실시간 환율이 표시되기를 원했습니다.

사용 제한 및 월별 요금과 함께 데이터를 제공할 수 있는 API가 있지만 Puppeteer를 사용하여 맞춤형 솔루션을 만들 수 있는 기회를 보았습니다. 사전에 약간의 시간을 투자함으로써 데이터를 무료로 스크랩하고 표시할 수 있었고 궁극적으로 고객이 반복적으로 발생하는 비용을 절약할 수 있었습니다.

클라이언트 웹사이트: Majesticpips.com

인형극 설정이 간단해졌습니다.

웹 스크래핑을 시작하기 전에 애플리케이션에 puppeteer를 설치해야 합니다.

문서에 설명된 대로

1단계

npm, Yarn 또는 pnpm을 선택하여 라이브러리를 설치하세요.

  • npm i puppeteer

  • 실 인형극 추가

  • pnpm 인형극 추가

이렇게 하면 설치 중에 호환되는 Chrome 버전이 다운로드되므로 초보자가 더 쉽게 작업을 빠르게 시작하고 실행할 수 있습니다.

더 노련한 개발자이고 작업하고 싶은 특정 Chrome/Chromium 버전이 있는 경우; 그런 다음 이 패키지를 설치하세요

  • npm i puppeteer-core

  • 실 추가 인형극 코어

  • pnpm puppeteer-core 추가

당신에게 가장 좋을 것입니다. 패키지는 puppeteer만 설치하고 크롬 버전은 사용자가 결정하도록 남겨두기 때문에 가벼울 것입니다.

처음 테스터인 경우 'puppeteer'를 설치하는 것이 더 나은 옵션입니다. 설정을 단순화하고 Chromium의 작동 버전을 보장하므로 스크립트 작성에 집중할 수 있습니다.

2단계

이제 JS 파일에서 노드 버전 12 이상의 ES 모듈 시스템(ES6 표준)을 사용하는 애플리케이션용 puppeteer를 가져오려고 합니다.

'puppeteer'에서 인형극을 가져옵니다. (권장)
또는
'puppeteer-core'에서 인형극 가져오기;

또는 이전 버전의 Node.js와도 호환되는 Node.js용 commonJs 모듈 시스템의 require 구문을 사용할 수 있습니다.

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' })
로그인 후 복사

혼합에 wait 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!

위 내용은 인형극으로 웹을 긁어보세요!의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!