Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

/screenshot - スクリーンショットを取得する

最終更新 Markdown で表示Agent セットアップ

/screenshot エンドポイントは、ページの HTML と JavaScript を処理して Web ページをレンダリングし、完全にレンダリングされたページのスクリーンショットを取得します。

このエンドポイントは、次の 2 通りの方法で使えます。

詳細は Quick Actions: 始める前に を参照してください。

エンドポイント

https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/screenshot

必須フィールド

url または html のいずれかを指定する必要があります。

  • url (string)
  • html (string)

よくある用途

  • ウェブサイト、ダッシュボード、レポート向けのプレビューを生成する
  • 自動テスト、QA、ビジュアルリグレッション向けにスクリーンショットを取得する

基本的な使い方

カスタム HTML からスクリーンショットを撮る

ページの HTML を Hello World! に設定し、スクリーンショットを撮影します。omitBackground オプションは、デフォルトの白い背景を隠し、透明度付きのスクリーンショットを撮れます。

curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/screenshot' \
  -H 'Authorization: Bearer <apiToken>' \
  -H 'Content-Type: application/json' \
  -d '{
    "html": "Hello World!",
    "screenshotOptions": {
      "omitBackground": true
    }
  }' \
  --output "screenshot.png"
import Cloudflare from "cloudflare";

const client = new Cloudflare({
	apiToken: process.env["CLOUDFLARE_API_TOKEN"],
});

const screenshot = await client.browserRendering.screenshot.create({
	account_id: process.env["CLOUDFLARE_ACCOUNT_ID"],
	html: "Hello World!",
	screenshotOptions: {
		omitBackground: true,
	},
});

console.log(screenshot.status);
interface Env {
	BROWSER: BrowserRun;
}

export default {
	async fetch(request, env): Promise<Response> {
		return await env.BROWSER.quickAction("screenshot", {
			html: "Hello World!",
			screenshotOptions: {
				omitBackground: true,
			},
		});
	},
} satisfies ExportedHandler<Env>;

URL からスクリーンショットを撮る

curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/screenshot' \
  -H 'Authorization: Bearer <apiToken>' \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://example.com"
  }' \
  --output "screenshot.png"

最終的なスクリーンショットを制御する clipcaptureBeyondViewportfullPage などのオプションは、エンドポイントの リファレンス を確認してください。

高度な使い方

認証が必要なページのスクリーンショットを取得する

一部の Web ページは、コンテンツを表示する前に認証が必要です。Browser Run は 3 つの認証方法をサポートし、すべての Quick Actions エンドポイントで使えます。各方法の簡易リファレンスは、Quick Actions で認証済みページをレンダリングするには? を参照してください。

ログインが必要なページにアクセスするには、有効なセッション Cookie を渡します。

curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/screenshot' \
  -H 'Authorization: Bearer <apiToken>' \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://example.com/protected-page",
    "cookies": [
      {
        "name": "session_id",
        "value": "your-session-cookie-value",
        "domain": "example.com",
        "path": "/"
      }
    ]
  }' \
  --output "authenticated-screenshot.png"

HTTP Basic Auth

HTTP Basic Authentication の背後にあるページには、authenticate パラメータを使います。

curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/screenshot' \
  -H 'Authorization: Bearer <apiToken>' \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://example.com/protected-page",
    "authenticate": {
      "username": "user",
      "password": "pass"
    }
  }' \
  --output "authenticated-screenshot.png"

トークンベースの認証

setExtraHTTPHeaders を使い、カスタムの認可ヘッダーを追加します。

curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/screenshot' \
  -H 'Authorization: Bearer <apiToken>' \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://example.com/protected-page",
    "setExtraHTTPHeaders": {
      "Authorization": "Bearer your-token"
    }
  }' \
  --output "authenticated-screenshot.png"

移動してフルページのスクリーンショットを取得する

https://cloudflare.com/ に移動し、ページサイズ(viewport)を変更します。アクティブなネットワーク接続がなくなるまで(waitUntil)、または最大 4500mstimeout)まで待ってから、fullPage のスクリーンショットを取得します。

curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/screenshot' \
  -H 'Authorization: Bearer <apiToken>' \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://cloudflare.com/",
    "screenshotOptions": {
       "fullPage": true
    },
    "viewport": {
      "width": 1280,
      "height": 720
    },
    "gotoOptions": {
      "waitUntil": "networkidle0",
      "timeout": 45000
    }
  }' \
  --output "advanced-screenshot.png"

ぼやけたスクリーンショットの解像度を改善する

ビューポートの幅と高さを大きくすると、スクリーンショットがぼやけたり、ピクセルが粗くなったりすることがあります。ブラウザーのデフォルトの deviceScaleFactor(既定値は 1)が、ビューポートに対して十分に高くない場合に起きます。

これを直すには、deviceScaleFactor の値を大きくします。

{
  "url": "https://cloudflare.com/",
  "viewport": {
    "width": 3600,
    "height": 2400,
    "deviceScaleFactor": 2
  }
}

CSS をカスタマイズし、カスタム JavaScript を埋め込む

ブラウザに https://example.com へ移動させ、カスタム JavaScript(addScriptTag)を埋め込み、インライン(addStyleTag.content)と外部スタイルシート(addStyleTag.url)の両方で追加スタイル(addStyleTag)を加えます。

curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/screenshot' \
  -H 'Authorization: Bearer <apiToken>' \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://example.com/",
    "addScriptTag": [
      { "content": "document.querySelector(`h1`).innerText = `Hello World!!!`" }
    ],
    "addStyleTag": [
      {
        "content": "div { background: linear-gradient(45deg, #2980b9  , #82e0aa  ); }"
      },
      {
        "url": "https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
      }
    ]
  }' \
  --output "screenshot.png"

selector オプションで特定の要素を取得する

Web ページ上の特定の要素のスクリーンショットを撮るには、有効な CSS セレクターを指定して selector オプションを使います。レンダリング時のページ寸法を制御するには、viewport も設定できます。

curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/screenshot' \
  -H 'Authorization: Bearer <apiToken>' \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://example.com",
    "selector": "#example_element_name",
    "viewport": {
      "width": 1200,
      "height": 1600
    }
  }' \
  --output "screenshot.png"

authenticate での HTTP 認証情報の設定、cookies の設定、gotoOptions でのページ読み込み制御など、ほかにも多くのオプションがあります。利用可能なすべてのパラメータは、エンドポイントの リファレンス を確認してください。

JavaScript が多いページの扱い

JavaScript が多いページや Single Page Application(SPA)では、デフォルトのページ読み込み動作だと、空または不完全な結果が返ることがあります。ブラウザーが、JavaScript によるコンテンツ描画が終わる前にページ読み込み完了とみなすためです。

いちばん簡単な対処は、gotoOptions.waitUntil パラメータを networkidle0 または networkidle2 に設定することです。

{
	"url": "https://example.com",
	"gotoOptions": {
		"waitUntil": "networkidle0"
	}
}

より速い応答が必要な場合、上級者はネットワーク活動がすべて止まるのを待つのではなく、waitForSelector で特定の要素を待てます。必要なコンテンツが読み込まれたことを示す CSS セレクターを把握している必要があります。詳細は Quick Actions のタイムアウト を参照してください。

カスタム User-Agent を設定する

JSON 本文のトップレベルパラメーターとして userAgent を渡すと、ページ単位で User-Agent を変更できます。対象サイトが User-Agent に応じて別のコンテンツを返す場合に便利です。

トラブルシューティング

質問がある場合やエラーが発生した場合は、Browser Run の FAQ とトラブルシューティングガイド を参照してください。

役に立ちましたか?