Skip to content

Commit 7309030

Browse files
author
stlc-bot
committed
feat(web): add URL-based scrape screenshot endpoint (#1150)
Stainless-Generated-From: cddaf198e50970afef181308f89cc32da4fb48b2
1 parent cd708ca commit 7309030

4 files changed

Lines changed: 202 additions & 1 deletion

File tree

‎.stats.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
configured_endpoints: 49
1+
configured_endpoints: 50

‎pkg/cmd/cmd.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ func init() {
109109
&webWebScrapeHTML,
110110
&webWebScrapeImages,
111111
&webWebScrapeMd,
112+
&webWebScrapeScreenshot,
112113
&webWebScrapeSitemap,
113114
},
114115
},

‎pkg/cmd/web.go‎

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1213,6 +1213,112 @@ var webWebScrapeMd = requestflag.WithInnerFlags(cli.Command{
12131213
},
12141214
})
12151215

1216+
var webWebScrapeScreenshot = requestflag.WithInnerFlags(cli.Command{
1217+
Name: "web-scrape-screenshot",
1218+
Usage: "Capture the given HTTP or HTTPS URL with configurable viewport, full-page\ncapture, wait time, popup handling, theme, scroll offset, cache age, country,\nand request timeout. Defaults to a 1920x1080 viewport, a 3-second wait, and a\ncache age of 1 day. With timeoutOpts.behavior=return-partial, a screenshot of\nthe page rendered so far may be returned; inspect finalDOMState to identify an\nincomplete render. Successful requests cost 1 credit; errors are not billed.",
1219+
Suggest: true,
1220+
Flags: []cli.Flag{
1221+
&requestflag.Flag[string]{
1222+
Name: "url",
1223+
Required: true,
1224+
QueryPath: "url",
1225+
},
1226+
&requestflag.Flag[bool]{
1227+
Name: "clear-popups",
1228+
Usage: "Optional parameter for comprehensive popup cleanup. If 'true', the browser dismisses detected cookie/consent UI and clears other detected obstructive popups and overlays before capture. If 'false' or not provided, this parameter requests no cleanup; handleCookiePopup can still request cookie/consent handling independently.",
1229+
Default: false,
1230+
QueryPath: "clearPopups",
1231+
},
1232+
&requestflag.Flag[string]{
1233+
Name: "color-scheme",
1234+
Usage: "Optional parameter to choose the site's visual theme in the screenshot. Use 'light' or 'dark' when the site offers both appearances.",
1235+
QueryPath: "colorScheme",
1236+
},
1237+
&requestflag.Flag[string]{
1238+
Name: "country",
1239+
Usage: "Fetch the target page through a residential proxy in this country (ISO 3166-1 alpha-2).",
1240+
QueryPath: "country",
1241+
},
1242+
&requestflag.Flag[string]{
1243+
Name: "full-screenshot",
1244+
Usage: "Optional parameter to determine screenshot type. If 'true', takes a full page screenshot capturing all content. If 'false' or not provided, takes a viewport screenshot (standard browser view).",
1245+
QueryPath: "fullScreenshot",
1246+
},
1247+
&requestflag.Flag[bool]{
1248+
Name: "handle-cookie-popup",
1249+
Usage: "Optional parameter to control cookie/consent popup handling. If 'true', we dismiss cookie banner before capture. If 'false' or not provided, captures the page without that step.",
1250+
Default: false,
1251+
QueryPath: "handleCookiePopup",
1252+
},
1253+
&requestflag.Flag[*int64]{
1254+
Name: "max-age-ms",
1255+
Usage: "Return a cached screenshot if a prior screenshot for the same parameters exists and is younger than this many milliseconds. Defaults to 1 day (86400000 ms) when omitted. Max is 30 days (2592000000 ms). Set to 0 to always capture fresh.",
1256+
Default: requestflag.Ptr[int64](86400000),
1257+
QueryPath: "maxAgeMs",
1258+
},
1259+
&requestflag.Flag[*int64]{
1260+
Name: "scroll-offset",
1261+
Usage: "Optional vertical scroll offset in pixels for capturing a long page in viewport-sized chunks. When provided, the full page is captured once and the returned image is the viewport-sized slice that begins at this Y offset (e.g. request scrollOffset=0, then 1080, then 2160 to walk a 1920x1080 landing page top to bottom). The final slice may be shorter than the viewport height. Takes precedence over fullScreenshot. Max: 100000.",
1262+
QueryPath: "scrollOffset",
1263+
},
1264+
&requestflag.Flag[[]string]{
1265+
Name: "tag",
1266+
Usage: "Comma-separated tags for tracking request usage. Up to 20 tags, each 1-50 characters.",
1267+
QueryPath: "tags",
1268+
},
1269+
&requestflag.Flag[map[string]any]{
1270+
Name: "timeout-opts",
1271+
Usage: "Optional request deadline and behavior on timeout. For GET requests, use timeoutOpts[milliseconds]=30000&timeoutOpts[behavior]=fail or a JSON-encoded timeoutOpts object.",
1272+
QueryPath: "timeoutOpts",
1273+
},
1274+
&requestflag.Flag[map[string]any]{
1275+
Name: "viewport",
1276+
Usage: "Optional browser viewport dimensions for the screenshot. Defaults to 1920x1080.",
1277+
Default: map[string]any{"width": 1920, "height": 1080},
1278+
QueryPath: "viewport",
1279+
},
1280+
&requestflag.Flag[*int64]{
1281+
Name: "wait-for-ms",
1282+
Usage: "Optional browser wait time in milliseconds after initial page load before taking the screenshot. Min: 0. Max: 30000 (30 seconds). Defaults to 3000 ms when omitted. When combined with timeoutOpts, timeoutOpts.milliseconds must be at least waitForMs + 10000 ms; a shorter deadline is rejected with 400 TIMEOUT_TOO_SHORT_FOR_WAIT.",
1283+
Default: requestflag.Ptr[int64](3000),
1284+
QueryPath: "waitForMs",
1285+
},
1286+
&requestflag.Flag[string]{
1287+
Name: "zdr",
1288+
Usage: "Set to enabled to bypass shared caches and omit request and response content from retained usage logs. Asset uploads are skipped, so hosted image URLs are omitted. Requires zero data retention to be enabled for your organization (contact support@context.dev), otherwise the request fails with ZDR_NOT_ENABLED. Successful ZDR responses include X-Context-ZDR: true.",
1289+
Default: "disabled",
1290+
QueryPath: "zdr",
1291+
},
1292+
},
1293+
Action: handleWebWebScrapeScreenshot,
1294+
HideHelpCommand: true,
1295+
}, map[string][]requestflag.HasOuterFlag{
1296+
"timeout-opts": {
1297+
&requestflag.InnerFlag[int64]{
1298+
Name: "timeout-opts.milliseconds",
1299+
Usage: "Request deadline in milliseconds. Maximum: 300000 (5 minutes).",
1300+
InnerField: "milliseconds",
1301+
},
1302+
&requestflag.InnerFlag[string]{
1303+
Name: "timeout-opts.behavior",
1304+
Usage: `What to do at the deadline. "fail" returns 408 REQUEST_TIMEOUT without charging credits. "return-partial" returns usable results collected so far; if none are available, the request still fails without charging credits. Partial results are not cached as complete results. "return-partial" requires milliseconds of at least 5000.`,
1305+
InnerField: "behavior",
1306+
},
1307+
},
1308+
"viewport": {
1309+
&requestflag.InnerFlag[int64]{
1310+
Name: "viewport.height",
1311+
Usage: "Viewport height in pixels.",
1312+
InnerField: "height",
1313+
},
1314+
&requestflag.InnerFlag[int64]{
1315+
Name: "viewport.width",
1316+
Usage: "Viewport width in pixels.",
1317+
InnerField: "width",
1318+
},
1319+
},
1320+
})
1321+
12161322
var webWebScrapeSitemap = requestflag.WithInnerFlags(cli.Command{
12171323
Name: "web-scrape-sitemap",
12181324
Usage: "Crawl an entire website's sitemap and return all discovered page URLs. Set\n`includeSubdomains=true` to also discover public pages and sitemaps on child\nhosts such as `docs.example.com` or `brand.example.com`. Pass `search` to have\nthe discovered URLs filtered down to the pages about a phrase (for example\n`pricing and plans` or `api authentication docs`), most relevant first — a\nsearched crawl scans the whole sitemap and costs 2 credits instead of 1.",
@@ -1782,6 +1888,47 @@ func handleWebWebScrapeMd(ctx context.Context, cmd *cli.Command) error {
17821888
})
17831889
}
17841890

1891+
func handleWebWebScrapeScreenshot(ctx context.Context, cmd *cli.Command) error {
1892+
client := contextdev.NewClient(getDefaultRequestOptions(cmd)...)
1893+
unusedArgs := cmd.Args().Slice()
1894+
1895+
if len(unusedArgs) > 0 {
1896+
return fmt.Errorf("Unexpected extra arguments: %v", unusedArgs)
1897+
}
1898+
1899+
options, err := flagOptions(
1900+
cmd,
1901+
apiquery.NestedQueryFormatBrackets,
1902+
apiquery.ArrayQueryFormatComma,
1903+
EmptyBody,
1904+
false,
1905+
)
1906+
if err != nil {
1907+
return err
1908+
}
1909+
1910+
params := contextdev.WebWebScrapeScreenshotParams{}
1911+
1912+
var res []byte
1913+
options = append(options, option.WithResponseBodyInto(&res))
1914+
_, err = client.Web.WebScrapeScreenshot(ctx, params, options...)
1915+
if err != nil {
1916+
return err
1917+
}
1918+
1919+
obj := gjson.ParseBytes(res)
1920+
format := cmd.Root().String("format")
1921+
explicitFormat := cmd.Root().IsSet("format")
1922+
transform := cmd.Root().String("transform")
1923+
return ShowJSON(obj, ShowJSONOpts{
1924+
ExplicitFormat: explicitFormat,
1925+
Format: format,
1926+
RawOutput: cmd.Root().Bool("raw-output"),
1927+
Title: "web web-scrape-screenshot",
1928+
Transform: transform,
1929+
})
1930+
}
1931+
17851932
func handleWebWebScrapeSitemap(ctx context.Context, cmd *cli.Command) error {
17861933
client := contextdev.NewClient(getDefaultRequestOptions(cmd)...)
17871934
unusedArgs := cmd.Args().Slice()

‎pkg/cmd/web_test.go‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -766,6 +766,59 @@ func TestWebWebScrapeMd(t *testing.T) {
766766
})
767767
}
768768

769+
func TestWebWebScrapeScreenshot(t *testing.T) {
770+
t.Skip("Mock server tests are disabled")
771+
t.Run("regular flags", func(t *testing.T) {
772+
mocktest.TestRunMockTestWithFlags(
773+
t,
774+
"--api-key", "string",
775+
"web", "web-scrape-screenshot",
776+
"--url", "https://example.com",
777+
"--clear-popups=true",
778+
"--color-scheme", "light",
779+
"--country", "de",
780+
"--full-screenshot", "true",
781+
"--handle-cookie-popup=true",
782+
"--max-age-ms", "0",
783+
"--scroll-offset", "0",
784+
"--tag", "production",
785+
"--tag", "team-alpha",
786+
"--timeout-opts", "{milliseconds: 1, behavior: fail}",
787+
"--viewport", "{height: 240, width: 240}",
788+
"--wait-for-ms", "0",
789+
"--zdr", "enabled",
790+
)
791+
})
792+
793+
t.Run("inner flags", func(t *testing.T) {
794+
// Check that inner flags have been set up correctly
795+
requestflag.CheckInnerFlags(webWebScrapeScreenshot)
796+
797+
// Alternative argument passing style using inner flags
798+
mocktest.TestRunMockTestWithFlags(
799+
t,
800+
"--api-key", "string",
801+
"web", "web-scrape-screenshot",
802+
"--url", "https://example.com",
803+
"--clear-popups=true",
804+
"--color-scheme", "light",
805+
"--country", "de",
806+
"--full-screenshot", "true",
807+
"--handle-cookie-popup=true",
808+
"--max-age-ms", "0",
809+
"--scroll-offset", "0",
810+
"--tag", "production",
811+
"--tag", "team-alpha",
812+
"--timeout-opts.milliseconds", "1",
813+
"--timeout-opts.behavior", "fail",
814+
"--viewport.height", "240",
815+
"--viewport.width", "240",
816+
"--wait-for-ms", "0",
817+
"--zdr", "enabled",
818+
)
819+
})
820+
}
821+
769822
func TestWebWebScrapeSitemap(t *testing.T) {
770823
t.Skip("Mock server tests are disabled")
771824
t.Run("regular flags", func(t *testing.T) {

0 commit comments

Comments
 (0)