Webページメタデータを除去するためのServerless関数の作成


最近では、ほとんどのウェブサイトはHTMLマークアップで直接コンテンツに関するメタデータを提供します.
この投稿は、このデータを使用してスクラップするために、Vercel Serverless関数を作成する方法を示しますMetascraper .

メタスクラム概要
Metascraper ルールベースのシステムは、一連の規則に従ってウェブサイトのコンテンツを検索することができます.として配布an open-source Node.js library .

Metascraper is baked by Microlink, which uses it internally in its browser automation product.



プロジェクト概要
任意のノードでMetascraperを使用できます.JSアプリケーション.
私の意見では、それを使う最も便利な方法は小さなノードの中にあります.入力URLを与えられたJSサーバは、出力として対象のウェブページについて構造化されたメタデータを返します.
このAPIは、次のAPIを作成することです.
  • Webサイトのscrapeに使用できるルートを公開します(例:api/scrape ).
  • 有効なURLがパラメータとして渡されたことを確認します?url クエリパラメータ).
  • ウェブサイトのコンテンツを取得します.
  • メタデータを抽出するためにウェブサイトコンテンツをMetascraperを呼び出します.
  • としてエンコードされたメタデータを返すjson を返します.

  • Vercel APIプロジェクトの設定
    このノードの目標を指定します.JSサーバは非常によくスコープされていて、リクエストが実行するのに長い時間がかかるとは期待していません.これはServerless/lambda関数として展開するための優れたフィットです.
    使いましょうVercel to deploy a serverless function , しかし、ノードをサポートする他のServerless APIプロバイダーでも同じことができます.JS (例えば、AWSラムダ、ファイアベース、netlifyなど).
    プロジェクトディレクトリを作成します.cd そして、NPMを使って初期化します:
    mkdir url-metadata-scraper && cd url-metadata-scraper
    npm init
    
    次に、インストール vercel devdependとして:
    npm install -D vercel 
    
    あなたのスタートスクリプトを更新しますpackage.json to "start": "vercel dev" ローカルの関数をローカルで実行します.
    最後に、作成api ディレクトリとscrape.js ファイルの内部:
    mkdir api && touch api/scrape.js
    
    // api/scrape.js
    // In Vercel, any file inside the folder "/api" is mapped to "/api/*" and 
    // will be treated as an API endpoint.
    
    
    // For an API route to work, you need to export a function as default (a.k.a request handler),
    // which then receives the following parameters:
    // - req: The request object.
    // - res: The response object.
    // See https://vercel.com/docs/serverless-functions/supported-languages#node.js for details.
    export default async function handler(req, res) {
      res.status(200).send(`Hello world!`)
    }
    
    あなたは今、あなたのコードをVercelに展開することができなければなりませんapi/scrape.js , だから今は何もしないだろう.
    これらの機会に私の試みへのアプローチはcreate a GitHub repo and connect it to Vercel そのため、各コミットでプロジェクトを自動的に展開することができますyou can also do it manually if you prefer .

    スクラップロジックの作成
    スクラップロジックを始めましょう.
    まず第一に、我々はgot npm package ウェブサイトのコンテンツを取得するにはmetascraper npm package メタデータを抽出するには、次の手順に従います.
    npm i got metascraper
    
    Metascraperメタデータを抽出する“ルールバンドル”を使用します.規則バンドルは、決定的なプロパティの周りのHTMLセレクタのコレクションです.
    Metascraper NPMパッケージには、ボックスから任意のルールバンドルが含まれていないので、手動で必要なそれぞれをインストールする必要があります.
    あなたは、チェックすることができます"Rules Bundles" section of the metascraper docs 利用可能なバンドルの一覧を見るには
    我々ができるだけ多くのメタデータを抽出するのを確実にするために、すべてを加えましょう:
    npm i metascraper-amazon metascraper-audio metascraper-author metascraper-clearbit metascraper-date metascraper-description metascraper-image metascraper-instagram metascraper-lang metascraper-logo metascraper-logo metascraper-publisher metascraper-readability metascraper-soundcloud metascraper-spotify metascraper-telegram metascraper-title metascraper-url metascraper-video metascraper-youtube
    
    我々は今、我々のAPIロジックを設定する準備が整いましたapi/scrape.js .
    簡単にするために、コード全体(コメント付き).
    // api/scrape.js
    // In Vercel, any file inside the folder "/api" is mapped to "/api/*" and 
    // will be treated as an API endpoint.
    
    const { parse } = require("url");
    const got = require("got");
    // Initialize metascraper passing in the list of rules bundles to use.
    const metascraper = require("metascraper")([
      require("metascraper-amazon")(),
      require("metascraper-audio")(),
      require("metascraper-author")(),
      require("metascraper-date")(),
      require("metascraper-description")(),
      require("metascraper-image")(),
      require("metascraper-instagram")(),
      require("metascraper-lang")(),
      require("metascraper-logo")(),
      require("metascraper-clearbit-logo")(),
      require("metascraper-logo-favicon")(),
      require("metascraper-publisher")(),
      require("metascraper-readability")(),
      require("metascraper-spotify")(),
      require("metascraper-title")(),
      require("metascraper-telegram")(),
      require("metascraper-url")(),
      require("metascraper-logo-favicon")(),
      require("metascraper-soundcloud")(),
      require("metascraper-video")(),
    ]);
    
    
    // For an API route to work, you need to export a function as default (a.k.a request handler),
    // which then receives the following parameters:
    // - req: The request object.
    // - res: The response object.
    // See https://vercel.com/docs/serverless-functions/supported-languages#node.js for details.
    export default async function handler(req, res) {
      // Parse the "?url" query parameter.
      const targetUrl = parse(req.url, true).query?.url;
    
      // Make sure the provided URL is valid.
      if (!targetUrl) {
        res
          .status(401)
          .send('Please provide a valid URL in the "url" query parameter.');
        return;
      }
    
      try {
        // Use the got library to fetch the website content.
        const { body: html, url } = await got(targetUrl);
        // Extract the metadata from the website content.
        const metadata = await metascraper({ html, url });
        // The Vercel Edge Network can cache the response at the edge in order to 
        // serve data to your users as fast as possible.
        // Here we're caching the response at the edge for 1 hour.
        // See https://vercel.com/docs/edge-network/caching for details.
        res.setHeader("Cache-Control", "s-maxage=3600");    
        // Make this API publicly accessible. 
        res.setHeader("Access-Control-Allow-Origin", "*");
        // Return the metadata as JSON
        res.status(200).json(metadata);
      } catch (err) {
        console.log(err);
        res.status(401).json({ error: `Unable to scrape "${url}".` });
      }
    }
    
    それです.
    走ることでnpm start (またはコードを展開して)/api/scrape 有効なURLを持つエンドポイントurl クエリパラメータを使用すると、WebページのメタデータでJSONレスポンスを取得する必要があります.
    例えば、http://localhost:3000/api/scrape?url=https://google.com 戻り値:
    {
      "lang": "en",
      "author": null,
      "title": "Google",
      "publisher": null,
      "image": "https://www.google.com/images/branding/googleg/1x/googleg_standard_color_128dp.png",
      "audio": null,
      "date": null,
      "description": "Search the world’s information, including webpages, images, videos and more. Google has many special features to help you find exactly what you’re looking for.",
      "video": null,
      "logo": "https://logo.clearbit.com/www.google.com",
      "url": "https://www.google.com/"
    }
    
    このプロジェクトのソースコード全体を見つけることができますon GitHub — それをフォークするか、試してみること自由に感じなさい!

    ボーナス:M 3 U 8サポート
    The metascraper-video パッケージは is-video タグが有効なビデオURLを含んでいるかどうかを判断するパッケージis-video に依存する video-extensions 有効なビデオ拡張子のリストを保持するパッケージ.
    残念ながらvideo-extensions パッケージはしばらく更新されていないので、サポートしていませんm3u8 ビデオの拡張子(これは最近、ウェブ上で人気のあるビデオの拡張です).
    までthis pull request がリリースされ、is-video の最新バージョンを使用するように更新されますvideo-extensions , 使えます patch-package 以下のdiffを手動でパッチするm3u8 サポートvideo-extensions に入れてpatches/video-extensions+1.1.0.patch ).
    diff --git a/node_modules/video-extensions/video-extensions.json b/node_modules/video-extensions/video-extensions.json
    index 0ad84d7..a115959 100644
    -------- a/node_modules/video-extensions/video-extensions.json
    +++ b/node_modules/video-extensions/video-extensions.json
    @@ -8,6 +8,7 @@
      "drc",
      "flv",
      "m2v",
    + "m3u8",
      "m4p",
      "m4v",
      "mkv",