パペッティアでウェブをこすりましょう!

WBOY
リリース: 2024-08-29 11:06:52
オリジナル
771 人が閲覧しました

Scrape the web with puppeteer!

Puppeteer フルガイド pt.1

Puppeteer: Web オートメーションのための強力なツール

今日のペースの速い Web 開発環境では、自動化が重要です。そこで Puppeteer が登場します。Google によって開発された Puppeteer は、開発者が JavaScript を使用して Chrome ブラウザを制御できるようにする強力な Node.js ライブラリです。効率を高めるためにヘッドレス モードで Web を操作する場合でも、視覚的なフィードバックを得るためにフルブラウザで Web を操作する場合でも、Puppeteer を使用すると、Web スクレイピングやテストなどのタスクをこれまでより簡単に自動化できます。 Puppeteer を使用すると、かつては手作業が必要でしたが、今ではスクリプトを実行するだけで済みます。

なぜウェブスクレイピングを行うのか?

最近のプロジェクトで、外国為替取引コミュニティのランディング ページを必要としているクライアントと協力しました。彼は、MarketWatch や Yahoo Finance で見られる株価ティッカーに似たものを望んでいましたが、株の代わりに、サイト全体に表示される 1 米ドルのリアルタイムの通貨換算レートを望んでいました。

データを提供できる API はありますが (使用制限や月額料金がかかります)、Puppeteer を使用してカスタム ソリューションを作成する機会があると考えました。事前に時間を投資することで、無料でデータを収集して表示することができ、最終的にクライアントを定期的なコストから節約することができました。

クライアントの Web サイト: Majesticpips.com

Puppeteer のセットアップが簡単になりました

Web のすべての栄光を得るためにスクレイピングを開始する前に、アプリケーションに puppeteer をインストールする必要があります。

ドキュメントの説明どおり

ステップ1

npm、yarn、または pnpm のいずれかを選択してライブラリをインストールします。

  • npm 私は人形遣いです

  • 糸を追加する人形遣い

  • pnpm 人形遣いを追加

これにより、インストール中に互換性のあるバージョンの Chrome がダウンロードされるため、初心者でもすぐに使い始めることが簡単になります。

あなたが経験豊富な開発者で、使用したい特定の chrome/chromium バージョンがある場合。次に、これらのパッケージをインストールします

  • npm i puppeteer-core

  • 糸追加 puppeteer-core

  • pnpm add puppeteer-core

これが最適です。puppeteer のみをインストールし、Chrome のバージョンはユーザーが決定するため、パッケージは軽量です。

初めてテスターを行う場合は、「puppeteer」をインストールすることをお勧めします。これによりセットアップが簡素化され、Chromium の動作バージョンが確保されるため、スクリプトの作成に集中できます。

ステップ2

ここで、JS ファイル上で、ノード バージョン 12 以降の ES モジュール システム (ES6 標準) を使用するアプリケーション用に puppeteer をインポートします。

「puppeteer」から puppeteer をインポートします。 (推奨)
または
'puppeteer-core' から puppeteer をインポートします;

または、古いバージョンの Node.js とも互換性のある Node.js の commonJs モジュール システムの require 構文を使用することもできます。

const puppeteer = require('puppeteer');
または
const puppeteer = require('puppeteer-core');

ステップ3

Puppeteer をインポートした後、Web スクレイピングを実行するコマンドの記述を開始できます。以下のコードは、使用する必要があるものを示しています。

ライブラリが提供するこれらのメソッドを使用してブラウザを起動します。

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

ブラウザが起動し、Web サーフィンの準備が整ったページができました。データを収集する Web サイトに移動しましょう。

この例では、qoutes Web サイトからデータをスクレイピングします。

 await page.goto(https://quotes.toscrape.com/)

 await page.screenshot({ path: 'screenshot.png' })
ログイン後にコピー

await page.screenshot({ path: 'screenshot.png' }) をミックスに追加しました。これは、すべてが計画どおりに進んでいることを確認するための優れたツールです。このコードが実行されると、スクレイピングしている Web サイトの現在の状態をキャプチャした画像ファイルがプロジェクト ディレクトリに作成されます。ファイル名はお好みに合わせて変更することもできます。

すべてを確認したら、ステップ 5 に進みます。

ステップ5

スクリプトが形になってきたので、Web ページからデータを抽出する重要な部分に進みましょう。これまでのスクリプトは次のようになります:

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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!