0

Scrape Elements

Published Oct 2, 2026

Load a page (url or raw html) and return the text, html and attributes of the elements matching each CSS selector. Extra fields go in options (gotoOptions, viewport, waitForSelector, userAgent, ...).

Script cloudflare Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 40 days ago
1
//native
2

3
/**
4
 * Scrape Elements
5
 * Load a page (url or raw html) and return the text, html and attributes of the elements matching each CSS selector. Extra fields go in options (gotoOptions, viewport, waitForSelector, userAgent, ...).
6
 */
7
export async function main(
8
  auth: RT.Cloudflare,
9
  url: string | undefined,
10
  html: string | undefined,
11
  selectors: string[],
12
  options: { [key: string]: any } | undefined
13
) {
14
  if (!url && !html) throw new Error("Either url or html is required")
15

16
  const response = await fetch(
17
    `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/browser-rendering/scrape`,
18
    {
19
      method: "POST",
20
      headers: {
21
        Authorization: `Bearer ${auth.token}`,
22
        "Content-Type": "application/json",
23
      },
24
      body: JSON.stringify({
25
        url: url || undefined,
26
        html: html || undefined,
27
        elements: selectors.map((selector) => ({ selector })),
28
        ...options,
29
      }),
30
    }
31
  )
32

33
  if (!response.ok) {
34
    throw new Error(`${response.status} ${await response.text()}`)
35
  }
36

37
  return await response.json()
38
}
39