Documentation
¶
Overview ¶
Package scrapfly provides a Go SDK for the Scrapfly.io web scraping API.
Scrapfly is a comprehensive web scraping API that handles proxies, browser rendering, anti-bot protection, and more. This SDK provides a simple and idiomatic Go interface to interact with the Scrapfly API for various web scraping tasks.
Features ¶
- Web scraping with automatic proxy rotation
- JavaScript rendering with headless browsers
- Anti-bot protection bypass (Unblocker)
- Screenshot capture with multiple formats
- AI-powered structured data extraction
- Session management for persistent browsing
- Concurrent scraping with rate limiting
- Caching and webhook support
Installation ¶
go get github.com/scrapfly/go-scrapfly
Quick Start ¶
Create a client and perform a simple scrape:
package main
import (
"fmt"
"log"
"github.com/scrapfly/go-scrapfly"
)
func main() {
// Create a new client
client, err := scrapfly.New("YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
// Configure the scrape request
config := &scrapfly.ScrapeConfig{
URL: "https://web-scraping.dev",
RenderJS: true,
Country: "us",
}
// Perform the scrape
result, err := client.Scrape(config)
if err != nil {
log.Fatal(err)
}
// Access the content
fmt.Println(result.Result.Content)
// Or use the built-in HTML parser
doc, err := result.Selector()
if err != nil {
log.Fatal(err)
}
title := doc.Find("title").First().Text()
fmt.Println("Title:", title)
}
Advanced Features ¶
JavaScript Rendering:
config := &scrapfly.ScrapeConfig{
URL: "https://web-scraping.dev",
RenderJS: true,
WaitForSelector: ".content",
RenderingWait: 2000,
AutoScroll: true,
}
Anti-bot bypass (the Unblocker) and proxy pools:
config := &scrapfly.ScrapeConfig{
URL: "https://web-scraping.dev",
Unblocker: scrapfly.BoolPtr(true),
ProxyPool: scrapfly.PublicResidentialPool,
}
ProxyPool is PublicDataCenterPool (the default), PublicResidentialPool or PublicTorPool. ASP is the deprecated alias of Unblocker.
Taking Screenshots:
config := &scrapfly.ScreenshotConfig{
URL: "https://web-scraping.dev",
Format: scrapfly.FormatPNG,
Capture: "fullpage",
Resolution: "1920x1080",
}
result, err := client.Screenshot(config)
if err != nil {
log.Fatal(err)
}
filePath, err := result.Save("screenshot")
Concurrent Scraping:
configs := []*scrapfly.ScrapeConfig{
{URL: "https://web-scraping.dev/page1"},
{URL: "https://web-scraping.dev/page2"},
{URL: "https://web-scraping.dev/page3"},
}
resultsChan := client.ConcurrentScrape(configs, 3)
for result := range resultsChan {
if result.Error != nil {
log.Printf("Error: %v", result.Error)
continue
}
// Process result
}
AI Data Extraction:
config := &scrapfly.ExtractionConfig{
Body: []byte("<html>...</html>"),
ContentType: "text/html",
ExtractionPrompt: "Extract product name, price, and description",
}
result, err := client.Extract(config)
Error Handling ¶
The SDK uses sentinel errors that can be checked with errors.Is():
result, err := client.Scrape(config)
if err != nil {
if errors.Is(err, scrapfly.ErrUpstreamClient) {
// Target website returned 4xx error
} else if errors.Is(err, scrapfly.ErrProxyFailed) {
// Proxy connection failed
} else if errors.Is(err, scrapfly.ErrUnblockerBypassFailed) {
// The unblocker could not get through the target's protection.
// Same value as the deprecated ErrASPBypassFailed.
} else if apiErr, ok := err.(*scrapfly.APIError); ok {
// Get detailed API error information
fmt.Printf("Status: %d, Message: %s\n", apiErr.HTTPStatusCode, apiErr.Message)
}
}
Debugging ¶
Enable debug logging to see detailed request information:
scrapfly.DefaultLogger.SetLevel(scrapfly.LevelDebug)
Enable debug mode in the API to access debug information in the dashboard:
config := &scrapfly.ScrapeConfig{
URL: "https://web-scraping.dev",
Debug: true,
}
Documentation ¶
For more information, visit:
- API Documentation: https://scrapfly.io/docs
- Web Scraping Guides: https://scrapfly.io/blog/tag/scrapeguide/
- Dashboard: https://scrapfly.io/dashboard
Example (BasicGet) ¶
basicGet demonstrates basic scraping with cache and the Unblocker
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"github.com/scrapfly/go-scrapfly"
)
// getApiKey falls back to a placeholder instead of exiting: log.Fatalf here would
// take the whole test binary down with it if an example ever regains an
// "// Output:" comment, hiding every other test in the package.
func getApiKey() string {
if apiKey := os.Getenv("SCRAPFLY_API_KEY"); apiKey != "" {
return apiKey
}
return "YOUR_API_KEY"
}
func main() {
apiKey := getApiKey()
client, err := scrapfly.New(apiKey)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
scrapeResult, err := client.Scrape(&scrapfly.ScrapeConfig{
URL: "https://httpbin.dev/html",
// anti-bot bypass
Unblocker: scrapfly.BoolPtr(true),
// server side cache - great for repeated requests
Cache: true,
CacheTTL: 3600, // in seconds
// CacheClear: true, // you can always clear the cache explicitly!
})
if err != nil {
log.Fatalf("scrape failed: %v", err)
}
// the scrape_result.Result contains all result details
fmt.Println("web log url:") // you can check web UI for request details:
fmt.Println(scrapeResult.Result.LogURL)
fmt.Println("\npage content:")
fmt.Println(scrapeResult.Result.Content)
fmt.Println("\nresponse headers:")
headersJSON, _ := json.MarshalIndent(scrapeResult.Result.ResponseHeaders, "", " ")
fmt.Println(string(headersJSON))
fmt.Println("\nresponse cookies:")
cookiesJSON, _ := json.MarshalIndent(scrapeResult.Result.Cookies, "", " ")
fmt.Println(string(cookiesJSON))
// Example output: scrapfly: 2025/10/26 05:39:16 [DEBUG] scraping url https://httpbin.dev/html
// scrapfly: 2025/10/26 05:39:19 [DEBUG] scrape log url: https://scrapfly.io/dashboard/monitoring/log/XXXXXXXXXXXXXXXXXXXXXXXXXX
// web log url:
// https://scrapfly.io/dashboard/monitoring/log/XXXXXXXXXXXXXXXXXXXXXXXXXX
// page content:
// <!DOCTYPE html>
// <html>
// <head>
// </head>
// <body>
// <h1>Herman Melville - Moby-Dick</h1>
// <div>
// <p>
// Availing himself of the mild, summer-cool weather that now reigned in these latitudes, and in preparation
// for the peculiarly active pursuits shortly to be anticipated, Perth, the begrimed, blistered old blacksmith,
// had not removed his portable forge to the hold again, after concluding his contributory work for Ahab's leg,
// but still retained it on deck, fast lashed to ringbolts by the foremast; being now almost incessantly
// invoked by the headsmen, and harpooneers, and bowsmen to do some little job for them; altering, or
// repairing, or new shaping their various weapons and boat furniture. Often he would be surrounded by an eager
// circle, all waiting to be served; holding boat-spades, pike-heads, harpoons, and lances, and jealously
// watching his every sooty movement, as he toiled. Nevertheless, this old man's was a patient hammer wielded
// by a patient arm. No murmur, no impatience, no petulance did come from him. Silent, slow, and solemn; bowing
// over still further his chronically broken back, he toiled away, as if toil were life itself, and the heavy
// beating of his hammer the heavy beating of his heart. And so it was.—Most miserable! A peculiar walk in this
// old man, a certain slight but painful appearing yawing in his gait, had at an early period of the voyage
// excited the curiosity of the mariners. And to the importunity of their persisted questionings he had finally
// given in; and so it came to pass that every one now knew the shameful story of his wretched fate. Belated,
// and not innocently, one bitter winter's midnight, on the road running between two country towns, the
// blacksmith half-stupidly felt the deadly numbness stealing over him, and sought refuge in a leaning,
// dilapidated barn. The issue was, the loss of the extremities of both feet. Out of this revelation, part by
// part, at last came out the four acts of the gladness, and the one long, and as yet uncatastrophied fifth act
// of the grief of his life's drama. He was an old man, who, at the age of nearly sixty, had postponedly
// encountered that thing in sorrow's technicals called ruin. He had been an artisan of famed excellence, and
// with plenty to do; owned a house and garden; embraced a youthful, daughter-like, loving wife, and three
// blithe, ruddy children; every Sunday went to a cheerful-looking church, planted in a grove. But one night,
// under cover of darkness, and further concealed in a most cunning disguisement, a desperate burglar slid into
// his happy home, and robbed them all of everything. And darker yet to tell, the blacksmith himself did
// ignorantly conduct this burglar into his family's heart. It was the Bottle Conjuror! Upon the opening of
// that fatal cork, forth flew the fiend, and shrivelled up his home. Now, for prudent, most wise, and economic
// reasons, the blacksmith's shop was in the basement of his dwelling, but with a separate entrance to it; so
// that always had the young and loving healthy wife listened with no unhappy nervousness, but with vigorous
// pleasure, to the stout ringing of her young-armed old husband's hammer; whose reverberations, muffled by
// passing through the floors and walls, came up to her, not unsweetly, in her nursery; and so, to stout
// Labor's iron lullaby, the blacksmith's infants were rocked to slumber. Oh, woe on woe! Oh, Death, why canst
// thou not sometimes be timely? Hadst thou taken this old blacksmith to thyself ere his full ruin came upon
// him, then had the young widow had a delicious grief, and her orphans a truly venerable, legendary sire to
// dream of in their after years; and all of them a care-killing competency.
// </p>
// </div>
// <hr>
// <h2>Heading Level 2</h2>
// <h3>Heading Level 3</h3>
// <p>This is a paragraph with <strong>bold</strong> and <em>italic</em> text.</p>
// <blockquote>
// <p>This is a blockquote for markdown testing.</p>
// </blockquote>
// <pre><code>// This is a code block
// function test() {
// return true;
// }
// </code></pre>
// <ul>
// <li>Unordered list item 1
// <ul>
// <li>Nested unordered item A</li>
// <li>Nested unordered item B</li>
// </ul>
// </li>
// <li>Unordered list item 2</li>
// </ul>
// <ol>
// <li>Ordered list item 1
// <ol>
// <li>Nested ordered item A</li>
// <li>Nested ordered item B</li>
// </ol>
// </li>
// <li>Ordered list item 2</li>
// </ol>
// <p>Link: <a href="https://httpbin.dev">httpbin.dev</a></p>
// <p>Image: <img src="https://httpbin.dev/image/png" alt="Test Image" width="100"></p>
// <h3>Vertical Table</h3>
// <table>
// <tr>
// <th>Header 1</th>
// <th>Header 2</th>
// </tr>
// <tr>
// <td>Cell 1</td>
// <td>Cell 2</td>
// </tr>xwx
// <tr>
// <td>Cell 3</td>
// <td>Cell 4</td>
// </tr>
// </table>
// <h3>Horizontal Table</h3>
// <table border="1">
// <tr>
// <th>Name</th>
// <th>Age</th>
// <th>Country</th>
// </tr>
// <tr>
// <td>Alice</td>
// <td>30</td>
// <td>USA</td>
// </tr>
// <tr>
// <td>Bob</td>
// <td>25</td>
// <td>UK</td>
// </tr>
// <tr>
// <td>Charlie</td>
// <td>35</td>
// <td>Canada</td>
// </tr>
// </table>
// <h3>Vertical Table</h3>
// <table border="1">
// <tr>
// <th>Field</th>
// <th>Value</th>
// </tr>
// <tr>
// <td>Name</td>
// <td>Alice</td>
// </tr>
// <tr>
// <td>Age</td>
// <td>30</td>
// </tr>
// <tr>
// <td>Country</td>
// <td>USA</td>
// </tr>
// </table>
// </body>
//
// </html>
//
// response headers:
// {
// "access-control-allow-credentials": "true",
// "access-control-allow-origin": "*",
// "alt-svc": "h3=\":443\"; ma=2592000",
// "content-security-policy": "frame-ancestors 'self' *.httpbin.dev; font-src 'self' *.httpbin.dev; default-src 'self' *.httpbin.dev; img-src 'self' *.httpbin.dev https://cdn.scrapfly.io; media-src 'self' *.httpbin.dev; object-src 'self' *.httpbin.dev https://web-scraping.dev; script-src 'self' 'unsafe-inline' 'unsafe-eval' *.httpbin.dev; style-src 'self' 'unsafe-inline' *.httpbin.dev https://unpkg.com; frame-src 'self' *.httpbin.dev https://web-scraping.dev; worker-src 'self' *.httpbin.dev; connect-src 'self' *.httpbin.dev",
// "content-type": "text/html; charset=utf-8",
// "date": "Sun, 26 Oct 2025 05:39:19 GMT",
// "permissions-policy": "fullscreen=(self), autoplay=*, geolocation=(), camera=()",
// "referrer-policy": "strict-origin-when-cross-origin",
// "strict-transport-security": "max-age=31536000; includeSubDomains; preload",
// "x-content-type-options": "nosniff",
// "x-xss-protection": "1; mode=block"
// }
//
// response cookies:
// []
}
Output:
Example (DownloadFile) ¶
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"github.com/scrapfly/go-scrapfly"
js_scenario "github.com/scrapfly/go-scrapfly/scenario"
)
// getApiKey falls back to a placeholder instead of exiting: log.Fatalf here would
// take the whole test binary down with it if an example ever regains an
// "// Output:" comment, hiding every other test in the package.
func getApiKey() string {
if apiKey := os.Getenv("SCRAPFLY_API_KEY"); apiKey != "" {
return apiKey
}
return "YOUR_API_KEY"
}
func main() {
apiKey := getApiKey()
client, err := scrapfly.New(apiKey)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
// Build a JavaScript scenario using the scenario builder
scenario, err := js_scenario.New().
Click("button[type='submit']").
Wait(2000).
Build()
if err != nil {
log.Fatalf("failed to build scenario: %v", err)
}
scrapeResult, err := client.Scrape(&scrapfly.ScrapeConfig{
URL: "https://web-scraping.dev/file-download",
// enable browsers:
RenderJS: true,
// this enables more options
// you can wait for some element to appear:
WaitForSelector: "#download-btn",
// you can wait explicitly for N seconds
RenderingWait: 3000, // 3 seconds
// you can control the browser through scenarios:
// https://scrapfly.io/docs/scrape-api/javascript-scenario
JSScenario: scenario,
// or even run any custom JS code!
})
if err != nil {
log.Fatalf("scrape failed: %v", err)
}
fmt.Println("attachments:")
attachmentsJSON, _ := json.MarshalIndent(scrapeResult.Result.BrowserData.Attachments, "", " ")
fmt.Println(string(attachmentsJSON))
// use the shortcut to save attachments to file:
paths, err := scrapeResult.SaveAttachments("./tests_output")
if err != nil {
log.Fatalf("failed to save attachments: %v", err)
}
for _, path := range paths {
fmt.Printf("Attachment saved to: %s\n", path)
}
// Example output: scrapfly: 2025/11/06 18:30:41 [DEBUG] scraping url https://web-scraping.dev/file-download
// scrapfly: 2025/11/06 18:30:55 [DEBUG] scrape log url: https://scrapfly.io/dashboard/monitoring/log/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// attachments:
// [
// {
// "content": "https://api.scrapfly.io/scrape/attachment/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/7024607f-f336-4a79-9841-5fc2bb06c41e",
// "content_type": "application/pdf",
// "filename": "download-sample.pdf",
// "id": "7024607f-f336-4a79-9841-5fc2bb06c41e",
// "size": 10360,
// "state": "completed",
// "suggested_filename": "download-sample.pdf",
// "url": "https://web-scraping.dev/api/download-file"
// }
// ]
// Attachment saved to: tests_output/download-sample.pdf
}
Output:
Example (ExtractionAutoExtract) ¶
extractionAutoExtract demonstrates automatic extraction using predefined models
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"github.com/scrapfly/go-scrapfly"
)
// getApiKey falls back to a placeholder instead of exiting: log.Fatalf here would
// take the whole test binary down with it if an example ever regains an
// "// Output:" comment, hiding every other test in the package.
func getApiKey() string {
if apiKey := os.Getenv("SCRAPFLY_API_KEY"); apiKey != "" {
return apiKey
}
return "YOUR_API_KEY"
}
func main() {
apiKey := getApiKey()
client, err := scrapfly.New(apiKey)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
// First, get HTML either from Web Scraping API or your own storage
scrapeResult, err := client.Scrape(&scrapfly.ScrapeConfig{
URL: "https://web-scraping.dev/product/1",
})
if err != nil {
log.Fatalf("scrape failed: %v", err)
}
html := scrapeResult.Result.Content
// Auto Extract - extract content using predefined models
productResult, err := client.Extract(&scrapfly.ExtractionConfig{
// identify content type like text/html or text/markdown etc.
ContentType: "text/html",
Body: []byte(html),
// define model type: product, article etc.
// see https://scrapfly.io/docs/extraction-api/automatic-ai#models
ExtractionModel: "product",
})
if err != nil {
log.Fatalf("extraction failed: %v", err)
}
fmt.Println("product auto extract:")
productResultJSON, _ := json.MarshalIndent(productResult, "", " ")
fmt.Println(string(productResultJSON))
// Example output: scrapfly: 2025/11/17 05:22:31 [DEBUG] scraping url https://web-scraping.dev/product/1
// scrapfly: 2025/11/17 05:22:35 [DEBUG] scrape log url: https://scrapfly.io/dashboard/monitoring/log/XXXXXX
// product auto extract:
// {
// "data": {
// "aggregate_rating": {
// "best_rating": 5,
// "rating_value": 4.7,
// "review_count": 10
// },
// "bidding": null,
// "brand": "ChocoDelight",
// "breadcrumbs": [
// {
// "link": "/",
// "name": "Home"
// },
// {
// "link": "/products",
// "name": "Products"
// },
// {
// "link": null,
// "name": "Box of Chocolate Candy"
// }
// ],
// "canonical_url": null,
// "color": null,
// "delivery": "1 Day shipping",
// "description": "Indulge your sweet tooth with our Box of Chocolate Candy. Each box contains an assortment of rich, flavorful chocolates with a smooth, creamy filling. Choose from a variety of flavors including zesty orange and sweet cherry. Whether you're looking for the perfect gift or just want to treat yourself, our Box of Chocolate Candy is sure to satisfy.",
// "description_markdown": "Indulge your sweet tooth with our Box of Chocolate Candy. Each box contains an assortment of rich, flavorful chocolates with a smooth, creamy filling. Choose from a variety of flavors including zesty orange and sweet cherry. Whether you're looking for the perfect gift or just want to treat yourself, our Box of Chocolate Candy is sure to satisfy.",
// "identifiers": {
// "ean13": null,
// "gtin14": null,
// "gtin8": null,
// "isbn10": null,
// "isbn13": null,
// "ismn": null,
// "issn": null,
// "mpn": null,
// "sku": "1",
// "upc": null
// },
// "images": [
// {
// "url": "https://www.web-scraping.dev/assets/products/orange-chocolate-box-small-1.webp"
// },
// {
// "url": "https://www.web-scraping.dev/assets/products/orange-chocolate-box-small-2.webp"
// },
// {
// "url": "https://www.web-scraping.dev/assets/products/orange-chocolate-box-small-3.webp"
// },
// {
// "url": "https://www.web-scraping.dev/assets/products/orange-chocolate-box-small-4.webp"
// }
// ],
// "main_category": "Products",
// "main_image": "https://www.web-scraping.dev/assets/products/orange-chocolate-box-small-1.webp",
// "name": "Box of Chocolate Candy",
// "offers": [
// {
// "availability": "available",
// "currency": "USD",
// "price": 9.99,
// "regular_price": 12.99
// }
// ],
// "related_products": [
// {
// "availability": "available",
// "description": null,
// "images": [
// {
// "url": "https://www.web-scraping.dev/assets/products/blue-potion.webp"
// }
// ],
// "link": "https://web-scraping.dev/product/17",
// "name": "Blue Energy Potion",
// "price": {
// "amount": 4.99,
// "currency": "USD",
// "raw": "4.99"
// }
// },
// {
// "availability": "available",
// "description": null,
// "images": [
// {
// "url": "https://www.web-scraping.dev/assets/products/teal-potion.webp"
// }
// ],
// "link": "https://web-scraping.dev/product/27",
// "name": "Teal Energy Potion",
// "price": {
// "amount": 4.99,
// "currency": "USD",
// "raw": "4.99"
// }
// },
// {
// "availability": "available",
// "description": null,
// "images": [
// {
// "url": "https://www.web-scraping.dev/assets/products/orange-chocolate-box-medium-1.webp"
// }
// ],
// "link": "https://web-scraping.dev/product/25",
// "name": "Box of Chocolate Candy",
// "price": {
// "amount": 24.99,
// "currency": "USD",
// "raw": "24.99"
// }
// },
// {
// "availability": "available",
// "description": null,
// "images": [
// {
// "url": "https://www.web-scraping.dev/assets/products/hiking-boots-1.webp"
// }
// ],
// "link": "https://web-scraping.dev/product/7",
// "name": "Hiking Boots for Outdoor Adventures",
// "price": {
// "amount": 89.99,
// "currency": "USD",
// "raw": "89.99"
// }
// }
// ],
// "secondary_category": null,
// "size": null,
// "sizes": null,
// "specifications": [
// {
// "name": "material",
// "value": "Premium quality chocolate"
// },
// {
// "name": "flavors",
// "value": "Available in Orange and Cherry flavors"
// },
// {
// "name": "sizes",
// "value": "Available in small, medium, and large boxes"
// },
// {
// "name": "brand",
// "value": "ChocoDelight"
// },
// {
// "name": "care instructions",
// "value": "Store in a cool, dry place"
// },
// {
// "name": "purpose",
// "value": "Ideal for gifting or self-indulgence"
// }
// ],
// "style": null,
// "url": "https://web-scraping.dev/product/1",
// "variants": [
// {
// "color": "orange",
// "offers": [],
// "sku": null,
// "url": "https://web-scraping.dev/product/1?variant=orange-small"
// },
// {
// "color": "orange",
// "offers": [],
// "sku": null,
// "url": "https://web-scraping.dev/product/1?variant=orange-medium"
// },
// {
// "color": "orange",
// "offers": [],
// "sku": null,
// "url": "https://web-scraping.dev/product/1?variant=orange-large"
// },
// {
// "color": "cherry",
// "offers": [],
// "sku": null,
// "url": "https://web-scraping.dev/product/1?variant=cherry-small"
// },
// {
// "color": "cherry",
// "offers": [],
// "sku": null,
// "url": "https://web-scraping.dev/product/1?variant=cherry-medium"
// },
// {
// "color": "cherry",
// "offers": [],
// "sku": null,
// "url": "https://web-scraping.dev/product/1?variant=cherry-large"
// }
// ]
// },
// "content_type": "application/json",
// "data_quality": {
// "errors": [
// "breadcrumbs[2].link: Input should be a valid string",
// "breadcrumbs[2].link: Input should be a valid string"
// ],
// "fulfilled": false,
// "fulfillment_percent": 69.57
// }
// }
}
Output:
Example (ExtractionLLM) ¶
extractionLLM demonstrates using the extraction API with LLM prompts
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"github.com/scrapfly/go-scrapfly"
)
// getApiKey falls back to a placeholder instead of exiting: log.Fatalf here would
// take the whole test binary down with it if an example ever regains an
// "// Output:" comment, hiding every other test in the package.
func getApiKey() string {
if apiKey := os.Getenv("SCRAPFLY_API_KEY"); apiKey != "" {
return apiKey
}
return "YOUR_API_KEY"
}
func main() {
apiKey := getApiKey()
client, err := scrapfly.New(apiKey)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
// First, get HTML either from Web Scraping API or your own storage
scrapeResult, err := client.Scrape(&scrapfly.ScrapeConfig{
URL: "https://web-scraping.dev/product/1",
})
if err != nil {
log.Fatalf("scrape failed: %v", err)
}
html := scrapeResult.Result.Content
// LLM Parsing - extract content using LLM queries
llmResult, err := client.Extract(&scrapfly.ExtractionConfig{
// identify content type like text/html or text/markdown etc.
ContentType: "text/html",
Body: []byte(html),
// use any prompt
ExtractionPrompt: "get product price only",
})
if err != nil {
log.Fatalf("extraction failed: %v", err)
}
fmt.Println("llm extraction:")
llmResultJSON, _ := json.MarshalIndent(llmResult, "", " ")
fmt.Println(string(llmResultJSON))
// You can also request LLM to output specific formats like JSON or CSV
llmFormatResult, err := client.Extract(&scrapfly.ExtractionConfig{
ContentType: "text/html",
Body: []byte(html),
// directly request format
ExtractionPrompt: "get product price and currency in JSON",
})
if err != nil {
log.Fatalf("extraction failed: %v", err)
}
fmt.Println("\nllm extraction in JSON:")
llmFormatResultJSON, _ := json.MarshalIndent(llmFormatResult, "", " ")
fmt.Println(string(llmFormatResultJSON))
// Example output: scrapfly: 2025/11/07 01:01:58 [DEBUG] scraping url https://web-scraping.dev/product/1
// scrapfly: 2025/11/07 01:02:00 [DEBUG] scrape log url: https://scrapfly.io/dashboard/monitoring/log/XXXXXXXXXXXXX
// llm extraction:
// {
// "data": "The price of the \"Box of Chocolate Candy\" is $9.99 from $12.99. The lowPrice is \"9.99\" and the highPrice is \"19.99\" according to the JSON-LD metadata.",
// "content_type": "text/plain"
// }
//
// llm extraction in JSON:
//
// {
// "data": {
// "product": "Box of Chocolate Candy",
// "similar_products": [
// {
// "currency": "USD",
// "price": "4.99",
// "product": "Dragon Energy Potion"
// },
// {
// "currency": "USD",
// "price": "89.99",
// "product": "Hiking Boots for Outdoor Adventures"
// },
// {
// "currency": "USD",
// "price": "4.99",
// "product": "Teal Energy Potion"
// },
// {
// "currency": "USD",
// "price": "14.99",
// "product": "Cat-Ear Beanie"
// }
// ],
// "variants": [
// {
// "currency": "USD",
// "price": "9.99",
// "variant": "orange, small"
// },
// {
// "currency": "USD",
// "price": "9.99",
// "variant": "orange, medium"
// },
// {
// "currency": "USD",
// "price": "9.99",
// "variant": "orange, large"
// },
// {
// "currency": "USD",
// "price": "9.99",
// "variant": "cherry, small"
// },
// {
// "currency": "USD",
// "price": "9.99",
// "variant": "cherry, medium"
// },
// {
// "currency": "USD",
// "price": "9.99",
// "variant": "cherry, large"
// }
// ]
// },
// "content_type": "application/json"
// }
}
Output:
Example (ExtractionTemplates) ¶
extractionTemplates demonstrates using extraction templates
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"github.com/scrapfly/go-scrapfly"
)
// getApiKey falls back to a placeholder instead of exiting: log.Fatalf here would
// take the whole test binary down with it if an example ever regains an
// "// Output:" comment, hiding every other test in the package.
func getApiKey() string {
if apiKey := os.Getenv("SCRAPFLY_API_KEY"); apiKey != "" {
return apiKey
}
return "YOUR_API_KEY"
}
func main() {
apiKey := getApiKey()
client, err := scrapfly.New(apiKey)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
// First, get HTML either from Web Scraping API or your own storage
scrapeResult, err := client.Scrape(&scrapfly.ScrapeConfig{
URL: "https://web-scraping.dev/reviews",
RenderJS: true,
WaitForSelector: ".review",
})
if err != nil {
log.Fatalf("scrape failed: %v", err)
}
html := scrapeResult.Result.Content
// Define your template, see https://scrapfly.io/docs/extraction-api/rules-and-template
template := map[string]interface{}{
"source": "html",
"selectors": []map[string]interface{}{
{
"name": "date_posted",
"type": "css",
"query": "[data-testid='review-date']::text",
"multiple": true,
"formatters": []map[string]interface{}{
{
"name": "datetime",
"args": map[string]interface{}{
"format": "%Y, %b %d — %A",
},
},
},
},
},
}
templateResult, err := client.Extract(&scrapfly.ExtractionConfig{
Body: []byte(html),
ContentType: "text/html",
// provide template:
ExtractionEphemeralTemplate: template,
})
if err != nil {
log.Fatalf("extraction failed: %v", err)
}
fmt.Println("template extract:")
templateResultJSON, _ := json.MarshalIndent(templateResult, "", " ")
fmt.Println(string(templateResultJSON))
// Example output: scrapfly: 2025/10/26 05:40:28 [DEBUG] scraping url https://web-scraping.dev/reviews
// scrapfly: 2025/10/26 05:40:35 [DEBUG] scrape log url: https://scrapfly.io/dashboard/monitoring/log/XXXXXXXXXXXXXXXXXXXXXXXXXX
// template extract:
// {
// "data": {
// "date_posted": [
// "2023, May 18 — Thursday",
// "2023, May 17 — Wednesday",
// "2023, May 16 — Tuesday",
// "2023, May 15 — Monday",
// "2023, May 15 — Monday",
// "2023, May 12 — Friday",
// "2023, May 10 — Wednesday",
// "2023, May 01 — Monday",
// "2023, May 01 — Monday",
// "2023, Apr 25 — Tuesday",
// "2023, Apr 25 — Tuesday",
// "2023, Apr 18 — Tuesday",
// "2023, Apr 12 — Wednesday",
// "2023, Apr 11 — Tuesday",
// "2023, Apr 10 — Monday",
// "2023, Apr 10 — Monday",
// "2023, Apr 09 — Sunday",
// "2023, Apr 07 — Friday",
// "2023, Apr 07 — Friday",
// "2023, Apr 05 — Wednesday"
// ]
// },
// "content_type": "application/json"
// }
}
Output:
Example (GetAccount) ¶
getAccount demonstrates fetching account information
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"github.com/scrapfly/go-scrapfly"
)
// getApiKey falls back to a placeholder instead of exiting: log.Fatalf here would
// take the whole test binary down with it if an example ever regains an
// "// Output:" comment, hiding every other test in the package.
func getApiKey() string {
if apiKey := os.Getenv("SCRAPFLY_API_KEY"); apiKey != "" {
return apiKey
}
return "YOUR_API_KEY"
}
func main() {
apiKey := getApiKey()
client, err := scrapfly.New(apiKey)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
account, err := client.Account()
if err != nil {
log.Fatalf("failed to get account: %v", err)
}
fmt.Println("Account:")
accountJSON, _ := json.MarshalIndent(account, "", " ")
fmt.Println(string(accountJSON))
// Example output: Account:
// {
// "account": {
// "account_id": "XX-XXX-4c01-a9X97-XXXX",
// "currency": "USD",
// "timezone": "Europe/Paris",
// "suspended": false,
// "suspension_reason": ""
// },
// "project": {
// "allow_extra_usage": true,
// "allowed_networks": [],
// "budget_limit": null,
// "budget_spent": null,
// "concurrency_limit": null,
// "name": "default",
// "quota_reached": false,
// "scrape_request_count": 307,
// "scrape_request_limit": null,
// "tags": []
// },
// "subscription": {
// "billing": {
// "current_extra_scrape_request_price": {
// "currency": "USD",
// "amount": 0
// },
// "extra_scrape_request_price_per_10k": {
// "currency": "USD",
// "amount": 0
// },
// "ongoing_payment": {
// "currency": "USD",
// "amount": 0
// },
// "plan_price": {
// "currency": "USD",
// "amount": 0
// }
// },
// "extra_scrape_allowed": false,
// "max_concurrency": 5,
// "period": {
// "start": "2025-08-01 00:06:34",
// "end": "2025-09-01 00:06:34"
// },
// "plan_name": "FREE",
// "usage": {
// "spider": {
// "current": 0,
// "limit": 1
// },
// "schedule": {
// "current": 0,
// "limit": 1
// },
// "scrape": {
// "concurrent_limit": 5,
// "concurrent_remaining": 5,
// "concurrent_usage": 0,
// "current": 307,
// "extra": 0,
// "limit": 1000,
// "remaining": 693
// }
// }
// }
// }
}
Output:
Example (JsRender) ¶
jsRender demonstrates JavaScript rendering with scenarios
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"github.com/scrapfly/go-scrapfly"
js_scenario "github.com/scrapfly/go-scrapfly/scenario"
)
// getApiKey falls back to a placeholder instead of exiting: log.Fatalf here would
// take the whole test binary down with it if an example ever regains an
// "// Output:" comment, hiding every other test in the package.
func getApiKey() string {
if apiKey := os.Getenv("SCRAPFLY_API_KEY"); apiKey != "" {
return apiKey
}
return "YOUR_API_KEY"
}
func main() {
apiKey := getApiKey()
client, err := scrapfly.New(apiKey)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
// Build a JavaScript scenario using the scenario builder
scenario, err := js_scenario.New().
Click("#load-more-reviews").
Wait(2000).
Build()
if err != nil {
log.Fatalf("failed to build scenario: %v", err)
}
scrapeResult, err := client.Scrape(&scrapfly.ScrapeConfig{
URL: "https://web-scraping.dev/product/1",
// enable browsers:
RenderJS: true,
// this enables more options
// you can wait for some element to appear:
WaitForSelector: ".review",
// you can wait explicitly for N seconds
RenderingWait: 3000, // 3 seconds
// you can control the browser through scenarios:
// https://scrapfly.io/docs/scrape-api/javascript-scenario
JSScenario: scenario,
// or even run any custom JS code!
JS: `return document.querySelector(".review").innerText`,
})
if err != nil {
log.Fatalf("scrape failed: %v", err)
}
// the scrape_result.Result contains all result details:
fmt.Println("web log url:") // you can check web UI for request details:
fmt.Println(scrapeResult.Result.LogURL)
fmt.Println("\npage content (first 1000 chars):")
content := scrapeResult.Result.Content
if len(content) > 1000 {
content = content[:1000] + "..."
}
fmt.Println(content)
fmt.Println("\nbrowser data capture:")
browserDataJSON, _ := json.MarshalIndent(scrapeResult.Result.BrowserData, "", " ")
fmt.Println(string(browserDataJSON))
// Example output: scrapfly: 2025/10/26 05:39:19 [DEBUG] scraping url https://web-scraping.dev/product/1
// scrapfly: 2025/10/26 05:39:34 [DEBUG] scrape log url: https://scrapfly.io/dashboard/monitoring/log/XXXXXXXXXXXXXXXXXXXXXXXXXX
// web log url:
// https://scrapfly.io/dashboard/monitoring/log/XXXXXXXXXXXXXXXXXXXXXXXXXX
//
// page content (first 1000 chars):
// <html lang="en"><head>
// <meta charset="utf-8">
// <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
// <link rel="stylesheet" href="https://web-scraping.dev/assets/css/main.css">
// <link rel="stylesheet" href="https://web-scraping.dev/assets/css/bootstrap.min.css">
// <link rel="stylesheet" href="https://web-scraping.dev/assets/css/bootstrap-icons.css">
// <link rel="stylesheet" href="https://web-scraping.dev/assets/css/highlight-nord.css">
// <link rel="icon" href="https://web-scraping.dev/assets/media/icon.png" type="image/png">
// <script src="https://web-scraping.dev/assets/js/cash.min.js"></script>
// <script src="https://web-scraping.dev/assets/js/main.js"></script>
// <script src="https://web-scraping.dev/assets/js/bootstrap.js"></script>
// <title>web-scraping.dev product Box of Chocolate Candy</title>
// <meta name="description" content="Mock product Box of Chocolate Candy page for web scraper testing">
// <meta property="og:sit...
// browser data capture:
//
// {
// "javascript_evaluation_result": "2022-07-22 \n\nAbsolutely delicious! The orange flavor is my favorite.",
// "js_scenario": {
// "duration": 3.0700000000000003,
// "executed": 2,
// "response": null,
// "steps": [
// {
// "action": "click",
// "config": {
// "ignore_if_not_visible": false,
// "multiple": false,
// "selector": "#load-more-reviews",
// "timeout": 3500
// },
// "duration": 1.07,
// "executed": true,
// "result": null,
// "success": true
// },
// {
// "action": "wait",
// "config": 2000,
// "duration": 2,
// "executed": true,
// "result": null,
// "success": true
// }
// ]
// },
// "local_storage_data": {},
// "session_storage_data": {},
// "websockets": [],
// "xhr_call": [
// {
// "body": null,
// "headers": {
// "Accept": "* /*",
// "Referer": "https://web-scraping.dev/product/1",
// "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36",
// "sec-ch-ua": "\"Google Chrome\";v=\"141\", \"Not?A_Brand\";v=\"8\", \"Chromium\";v=\"141\"",
// "sec-ch-ua-mobile": "?0",
// "sec-ch-ua-platform": "\"macOS\"",
// "x-csrf-token": "secret-csrf-token-123"
// },
// "method": "GET",
// "response": {
// "body": "{\"order\":\"asc\",\"category\":null,\"total_results\":10,\"next_url\":null,\"results\":[{\"id\":\"chocolate-candy-box-6\",\"text\":\"Bought the large box, and it's lasted quite a while. Great for when you need a sweet treat.\",\"rating\":5,\"date\":\"2022-12-18\"},{\"id\":\"chocolate-candy-box-7\",\"text\":\"These chocolates are so tasty! Love the variety of flavors.\",\"rating\":5,\"date\":\"2023-01-24\"},{\"id\":\"chocolate-candy-box-8\",\"text\":\"The box is nicely packaged, making it a great gift option.\",\"rating\":5,\"date\":\"2023-02-15\"},{\"id\":\"chocolate-candy-box-9\",\"text\":\"The orange flavor wasn't my favorite, but the cherry ones are great.\",\"rating\":4,\"date\":\"2023-03-20\"},{\"id\":\"chocolate-candy-box-10\",\"text\":\"Delicious chocolates, and the box is pretty substantial. It'd make a nice gift.\",\"rating\":5,\"date\":\"2023-04-18\"}],\"page_number\":2,\"page_size\":5,\"page_total\":2}",
// "content_encoding": null,
// "content_type": "application/json",
// "duration": 0,
// "format": "text",
// "headers": {
// "alt-svc": "h3=\":443\"; ma=2592000",
// "content-length": "839",
// "content-type": "application/json",
// "date": "Sun, 26 Oct 2025 05:39:31 GMT",
// "permissions-policy": "fullscreen=(self), autoplay=*, geolocation=(), camera=()",
// "referrer-policy": "strict-origin-when-cross-origin",
// "server": "uvicorn",
// "strict-transport-security": "max-age=31536000; includeSubDomains; preload",
// "x-content-type-options": "nosniff",
// "x-xss-protection": "1; mode=block"
// },
// "status": 200
// },
// "type": "fetch",
// "url": "https://web-scraping.dev/api/reviews?product_id=1\u0026page=2"
// }
// ]
// }
}
Output:
Example (ScrapeExtraction) ¶
scrapeExtraction demonstrates scraping with inline extraction using LLM prompts
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"github.com/scrapfly/go-scrapfly"
)
// getApiKey falls back to a placeholder instead of exiting: log.Fatalf here would
// take the whole test binary down with it if an example ever regains an
// "// Output:" comment, hiding every other test in the package.
func getApiKey() string {
if apiKey := os.Getenv("SCRAPFLY_API_KEY"); apiKey != "" {
return apiKey
}
return "YOUR_API_KEY"
}
func main() {
apiKey := getApiKey()
client, err := scrapfly.New(apiKey)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
scrapeResult, err := client.Scrape(&scrapfly.ScrapeConfig{
URL: "https://web-scraping.dev/product/1",
// enable browsers:
RenderJS: true,
// use LLM prompt for auto parsing
ExtractionPrompt: "Extract the product specification in json format",
})
if err != nil {
log.Fatalf("scrape failed: %v", err)
}
// access the extraction result
fmt.Println("extraction result:")
extractedDataJSON, _ := json.MarshalIndent(scrapeResult.Result.ExtractedData, "", " ")
fmt.Println(string(extractedDataJSON))
// Example output: scrapfly: 2025/11/07 01:01:46 [DEBUG] scraping url https://web-scraping.dev/product/1
// scrapfly: 2025/11/07 01:01:58 [DEBUG] scrape log url: https://scrapfly.io/dashboard/monitoring/log/XXXXXXXXXXXXX
// extraction result:
// {
// "data": {
// "product": {
// "aggregateRating": {
// "ratingValue": "4.7",
// "reviewCount": "10"
// },
// "brand": "ChocoDelight",
// "description": "Indulge your sweet tooth with our Box of Chocolate Candy. Each box contains an assortment of rich, flavorful chocolates with a smooth, creamy filling. Choose from a variety of flavors including zesty orange and sweet cherry. Whether you're looking for the perfect gift or just want to treat yourself, our Box of Chocolate Candy is sure to satisfy.",
// "features": {
// "care instructions": "Store in a cool, dry place",
// "flavors": "Available in Orange and Cherry flavors",
// "material": "Premium quality chocolate",
// "purpose": "Ideal for gifting or self-indulgence",
// "sizes": "Available in small, medium, and large boxes"
// },
// "image": "https://web-scraping.dev/assets/products/orange-chocolate-box-medium-1.webp",
// "name": "Box of Chocolate Candy",
// "offers": {
// "availability": "InStock",
// "highPrice": "19.99",
// "lowPrice": "9.99",
// "priceCurrency": "USD"
// },
// "packs": [
// {
// "Delivery Type": "1 Day shipping",
// "Package Dimension": "100x230 cm",
// "Package Weight": "1,00 kg",
// "Variants": "6 available",
// "Version": "Pack 1"
// },
// {
// "Delivery Type": "1 Day shipping",
// "Package Dimension": "200x460 cm",
// "Package Weight": "2,11 kg",
// "Variants": "6 available",
// "Version": "Pack 2"
// },
// {
// "Delivery Type": "1 Day shipping",
// "Package Dimension": "300x690 cm",
// "Package Weight": "3,22 kg",
// "Variants": "6 available",
// "Version": "Pack 3"
// },
// {
// "Delivery Type": "1 Day shipping",
// "Package Dimension": "400x920 cm",
// "Package Weight": "4,33 kg",
// "Variants": "6 available",
// "Version": "Pack 4"
// },
// {
// "Delivery Type": "1 Day shipping",
// "Package Dimension": "500x1150 cm",
// "Package Weight": "5,44 kg",
// "Variants": "6 available",
// "Version": "Pack 5"
// }
// ],
// "reviews": [
// {
// "datePublished": "2022-07-22",
// "ratingValue": "5",
// "reviewBody": "Absolutely delicious! The orange flavor is my favorite."
// },
// {
// "datePublished": "2022-08-16",
// "ratingValue": "4",
// "reviewBody": "I bought these as a gift, and they were well received. Will definitely purchase again."
// },
// {
// "datePublished": "2022-09-10",
// "ratingValue": "5",
// "reviewBody": "Nice variety of flavors. The chocolate is rich and smooth."
// },
// {
// "datePublished": "2022-10-02",
// "ratingValue": "5",
// "reviewBody": "The cherry flavor is amazing. Will be buying more."
// },
// {
// "datePublished": "2022-11-05",
// "ratingValue": "4",
// "reviewBody": "A bit pricey, but the quality of the chocolate is worth it."
// }
// ],
// "variants": [
// "orange, small",
// "orange, medium",
// "orange, large",
// "cherry, small",
// "cherry, medium",
// "cherry, large"
// ]
// }
// },
// "content_type": "application/json"
// }
}
Output:
Example (Screenshot) ¶
screenshot demonstrates capturing screenshots
package main
import (
"fmt"
"log"
"os"
"github.com/scrapfly/go-scrapfly"
)
// getApiKey falls back to a placeholder instead of exiting: log.Fatalf here would
// take the whole test binary down with it if an example ever regains an
// "// Output:" comment, hiding every other test in the package.
func getApiKey() string {
if apiKey := os.Getenv("SCRAPFLY_API_KEY"); apiKey != "" {
return apiKey
}
return "YOUR_API_KEY"
}
func main() {
apiKey := getApiKey()
client, err := scrapfly.New(apiKey)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
screenshotResult, err := client.Screenshot(&scrapfly.ScreenshotConfig{
URL: "https://web-scraping.dev/product/1",
// by default 1920x1080 will be captured but resolution can take any value
Resolution: "540x1200", // for example - tall smartphone viewport
// to capture all visible parts use capture with full page
Capture: "fullpage",
// you can also capture specific elements with css or xpath
// WaitForSelector: "#reviews", // wait for review to load
// Capture: "#reviews", // capture only reviews element
// for pages that require scrolling to load elements (like endless paging) use
AutoScroll: true,
// Simulate vision deficiency (new)
VisionDeficiencyType: scrapfly.VisionDeficiencyTypeBlurredVision,
})
if err != nil {
log.Fatalf("screenshot failed: %v", err)
}
fmt.Println("captured screenshot:")
fmt.Printf("Format: %s, Size: %d bytes\n", screenshotResult.Metadata.ExtensionName, len(screenshotResult.Image))
// use the shortcut to save screenshots to file:
filePath, err := screenshotResult.Save("screenshot")
if err != nil {
log.Fatalf("failed to save screenshot: %v", err)
}
fmt.Printf("saved screenshot to %s\n", filePath)
// Example output: captured screenshot:
// Format: jpeg, Size: 586399 bytes
// saved screenshot to screenshot.jpeg
}
Output:
Index ¶
- Constants
- Variables
- func BoolPtr(v bool) *bool
- func GetAnyEnumFor[V Enumerable[T], T fmt.Stringer]() []any
- func GetEnumFor[V Enumerable[T], T fmt.Stringer]() []T
- func IsValidEnumType[T fmt.Stringer](f T) bool
- func ProjectSalt(apiKey string) string
- func ValidateAlertCreate(req AlertCreateRequest) error
- func ValidateEnums(s interface{}) error
- func ValidateExclusiveFields(s interface{}) error
- func ValidateRequiredFields(s interface{}) error
- type APIError
- type APIErrorDetails
- type Account
- type AccountData
- type Alert
- type AlertComparator
- type AlertCountActiveResult
- type AlertCreateRequest
- type AlertDeleteResult
- type AlertListOptions
- type AlertMetricFamily
- type AlertNoDataPolicy
- type AlertNotifyChannel
- type AlertNotifyKind
- type AlertPreviewFiredMarker
- type AlertPreviewRequest
- type AlertPreviewResponse
- type AlertSeriesPoint
- type AlertSeriesResponse
- type AlertSnoozeRequest
- type AlertState
- type AlertTestResult
- type AlertTransitionMarker
- type AlertUpdateRequest
- type Attachment
- type BatchFormat
- type BatchOptions
- type BatchResult
- type BrowserData
- type BrowserDownload
- type CDPSender
- type CDPSenderFunc
- type CacheContext
- type ChromedpExecutor
- type ClassifyRequest
- type ClassifyResult
- type Client
- func (c *Client) APIKey() string
- func (c *Client) Account() (*AccountData, error)
- func (c *Client) CancelSchedule(id string) error
- func (c *Client) Classify(ctx context.Context, req *ClassifyRequest) (*ClassifyResult, error)
- func (c *Client) CloudBrowser(config *CloudBrowserConfig) string
- func (c *Client) CloudBrowserExtensionDelete(extensionID string) (map[string]interface{}, error)
- func (c *Client) CloudBrowserExtensionGet(extensionID string) (map[string]interface{}, error)
- func (c *Client) CloudBrowserExtensionList() (map[string]interface{}, error)
- func (c *Client) CloudBrowserExtensionUpload(filePath string) (map[string]interface{}, error)
- func (c *Client) CloudBrowserPlayback(runID string) (map[string]interface{}, error)
- func (c *Client) CloudBrowserProjectSalt() string
- func (c *Client) CloudBrowserSessionStop(sessionID string) error
- func (c *Client) CloudBrowserSessions() (map[string]interface{}, error)
- func (c *Client) CloudBrowserUnblock(config UnblockConfig) (*UnblockResult, error)
- func (c *Client) CloudBrowserVNCPassword(config *CloudBrowserConfig) (string, error)
- func (c *Client) CloudBrowserVaultCreate(name, description string) (map[string]interface{}, error)
- func (c *Client) CloudBrowserVaultDelete(vaultID string) (map[string]interface{}, error)
- func (c *Client) CloudBrowserVaultGet(vaultID string) (map[string]interface{}, error)
- func (c *Client) CloudBrowserVaultItemCreate(vaultID, vaultKey string, item map[string]interface{}) (map[string]interface{}, error)
- func (c *Client) CloudBrowserVaultItemDelete(vaultID, itemID string) (map[string]interface{}, error)
- func (c *Client) CloudBrowserVaultItemList(vaultID string) (map[string]interface{}, error)
- func (c *Client) CloudBrowserVaultItemUpdate(vaultID, itemID, vaultKey string, patch map[string]interface{}) (map[string]interface{}, error)
- func (c *Client) CloudBrowserVaultList() (map[string]interface{}, error)
- func (c *Client) CloudBrowserVaultRotate(vaultID, currentVaultKey string) (map[string]interface{}, error)
- func (c *Client) CloudBrowserVaultServiceLink(vaultID, vaultKey string, linkedService CloudBrowserLinkedService, ...) (map[string]interface{}, error)
- func (c *Client) CloudBrowserVaultServiceSync(vaultID, vaultKey string) (map[string]interface{}, error)
- func (c *Client) CloudBrowserVaultServiceTest(vaultID, vaultKey string, linkedService CloudBrowserLinkedService, ...) (map[string]interface{}, error)
- func (c *Client) CloudBrowserVaultServiceUnlink(vaultID string, keepItems bool) (map[string]interface{}, error)
- func (c *Client) CloudBrowserVaultServiceUpdate(vaultID, vaultKey, token string, serviceData map[string]interface{}) (map[string]interface{}, error)
- func (c *Client) CloudBrowserVaultUpdate(vaultID string, name, description string) (map[string]interface{}, error)
- func (c *Client) CloudBrowserVideo(runID string) ([]byte, error)
- func (c *Client) CloudBrowserWaitForPlayback(runID string, timeout, fallbackInterval time.Duration) (map[string]interface{}, error)
- func (c *Client) ConcurrentScrape(configs []*ScrapeConfig, concurrencyLimit int) <-chan ConcurrentScrapeResult
- func (c *Client) CountActiveAlerts(projectUUID string) (*AlertCountActiveResult, error)
- func (c *Client) CrawlArtifact(uuid string, artifactType CrawlerArtifactType) (*CrawlerArtifact, error)
- func (c *Client) CrawlCancel(uuid string) error
- func (c *Client) CrawlContentsBatch(uuid string, urls []string, formats []CrawlerContentFormat) (map[string]map[string]string, error)
- func (c *Client) CrawlContentsJSON(uuid string, format CrawlerContentFormat, opts *CrawlContentsOptions) (*CrawlerContents, error)
- func (c *Client) CrawlContentsPlain(uuid, targetURL string, format CrawlerContentFormat) (string, error)
- func (c *Client) CrawlExtract(uuid, prompt string, schema map[string]interface{}, opts *CrawlExtractOptions) (*CrawlerExtractResponse, error)
- func (c *Client) CrawlPrompt(uuid, prompt string, opts *CrawlPromptOptions, handler CrawlPromptHandler) error
- func (c *Client) CrawlPromptAnswer(uuid, prompt string, opts *CrawlPromptOptions) (*CrawlerPromptAnswer, error)
- func (c *Client) CrawlRefreshHistory(uuid string, limit int) ([]CrawlerRefreshEntry, error)
- func (c *Client) CrawlRefreshNow(uuid string) (*CrawlerRefreshState, error)
- func (c *Client) CrawlRefreshSettings(uuid string, settings CrawlRefreshSettings) (*CrawlerRefreshState, error)
- func (c *Client) CrawlSearch(uuid, query string, opts *CrawlSearchOptions) (*CrawlerSearchResponse, error)
- func (c *Client) CrawlStatus(uuid string) (*CrawlerStatus, error)
- func (c *Client) CrawlURLs(uuid string, opts *CrawlURLsOptions) (*CrawlerURLs, error)
- func (c *Client) CrawlsExtract(crawlIDs []string, prompt string, schema map[string]interface{}, ...) (*CrawlerExtractResponse, error)
- func (c *Client) CrawlsPrompt(crawlIDs []string, prompt string, opts *CrawlPromptOptions, ...) error
- func (c *Client) CrawlsPromptAnswer(crawlIDs []string, prompt string, opts *CrawlPromptOptions) (*CrawlerPromptAnswer, error)
- func (c *Client) CrawlsSearch(crawlIDs []string, query string, opts *CrawlSearchOptions) (*CrawlerSearchResponse, error)
- func (c *Client) CreateAlert(req AlertCreateRequest) (*Alert, error)
- func (c *Client) CreateCrawlerSchedule(crawlerConfig map[string]interface{}, req *CreateScheduleRequest) (*Schedule, error)
- func (c *Client) CreateScrapeSchedule(scrapeConfig map[string]interface{}, req *CreateScheduleRequest) (*Schedule, error)
- func (c *Client) CreateScreenshotSchedule(screenshotConfig map[string]interface{}, req *CreateScheduleRequest) (*Schedule, error)
- func (c *Client) DeleteAlert(alertUUID string) (*AlertDeleteResult, error)
- func (c *Client) ExecuteSchedule(id string) (*Schedule, error)
- func (c *Client) Extract(config *ExtractionConfig) (*ExtractionResult, error)
- func (c *Client) GetAlert(alertUUID string) (*Alert, error)
- func (c *Client) GetAlertSeries(alertUUID string, rangeMinutes int) (*AlertSeriesResponse, error)
- func (c *Client) GetBrowserMonitoringMetrics(opts CloudBrowserMonitoringOptions) (map[string]any, error)
- func (c *Client) GetBrowserMonitoringTimeseries(opts CloudBrowserMonitoringOptions) (map[string]any, error)
- func (c *Client) GetCrawlerMonitoringMetrics(opts MonitoringMetricsOptions) (map[string]any, error)
- func (c *Client) GetCrawlerMonitoringTargetMetrics(opts MonitoringTargetMetricsOptions) (map[string]any, error)
- func (c *Client) GetExtractionMonitoringMetrics(opts MonitoringMetricsOptions) (map[string]any, error)
- func (c *Client) GetExtractionMonitoringTargetMetrics(opts MonitoringTargetMetricsOptions) (map[string]any, error)
- func (c *Client) GetMonitoringMetrics(opts MonitoringMetricsOptions) (map[string]any, error)
- func (c *Client) GetMonitoringTargetMetrics(opts MonitoringTargetMetricsOptions) (map[string]any, error)
- func (c *Client) GetSchedule(id string) (*Schedule, error)
- func (c *Client) GetScreenshotMonitoringMetrics(opts MonitoringMetricsOptions) (map[string]any, error)
- func (c *Client) GetScreenshotMonitoringTargetMetrics(opts MonitoringTargetMetricsOptions) (map[string]any, error)
- func (c *Client) HTTPClient() *http.Client
- func (c *Client) ListAlertMetricFamilies() ([]AlertMetricFamily, error)
- func (c *Client) ListAlerts(opts AlertListOptions) ([]Alert, error)
- func (c *Client) ListCrawlerSchedules(opts *ListSchedulesOptions) ([]Schedule, error)
- func (c *Client) ListSchedules(opts *ListSchedulesOptions) ([]Schedule, error)
- func (c *Client) ListScrapeSchedules(opts *ListSchedulesOptions) ([]Schedule, error)
- func (c *Client) ListScreenshotSchedules(opts *ListSchedulesOptions) ([]Schedule, error)
- func (c *Client) PauseSchedule(id string) (*Schedule, error)
- func (c *Client) PreviewAlert(req AlertPreviewRequest) (*AlertPreviewResponse, error)
- func (c *Client) ResumeSchedule(id string) (*Schedule, error)
- func (c *Client) Scrape(config *ScrapeConfig) (*ScrapeResult, error)
- func (c *Client) ScrapeBatch(configs []*ScrapeConfig) (<-chan BatchResult, error)
- func (c *Client) ScrapeBatchWithOptions(configs []*ScrapeConfig, opts BatchOptions) (<-chan BatchResult, error)
- func (c *Client) ScrapeProxified(config *ScrapeConfig) (*http.Response, error)
- func (c *Client) Screenshot(config *ScreenshotConfig) (*ScreenshotResult, error)
- func (c *Client) SetAPIKey(key string)
- func (c *Client) SetCloudBrowserHost(host string)
- func (c *Client) SetHTTPClient(httpClient *http.Client)
- func (c *Client) SnoozeAlert(alertUUID string, req AlertSnoozeRequest) (*Alert, error)
- func (c *Client) StartCrawl(config *CrawlerConfig) (*CrawlerStartResponse, error)
- func (c *Client) TestAlert(alertUUID string) (*AlertTestResult, error)
- func (c *Client) UnsnoozeAlert(alertUUID string) (*Alert, error)
- func (c *Client) UpdateAlert(alertUUID string, req AlertUpdateRequest) (*Alert, error)
- func (c *Client) UpdateSchedule(id string, req *UpdateScheduleRequest) (*Schedule, error)
- func (c *Client) VerifyAPIKey() (*VerifyAPIKeyResult, error)
- type CloudBrowserConfig
- type CloudBrowserDownloads
- func (d *CloudBrowserDownloads) List(ctx context.Context) ([]BrowserDownload, error)
- func (d *CloudBrowserDownloads) Metadata(ctx context.Context) (map[string]int64, error)
- func (d *CloudBrowserDownloads) Read(ctx context.Context, download BrowserDownload) ([]byte, error)
- func (d *CloudBrowserDownloads) Save(ctx context.Context, download BrowserDownload, path string) (string, error)
- func (d *CloudBrowserDownloads) SaveAll(ctx context.Context, dir string) ([]string, error)
- func (d *CloudBrowserDownloads) WaitFor(ctx context.Context, filename string, interval time.Duration) (int64, error)
- func (d *CloudBrowserDownloads) WriteTo(ctx context.Context, download BrowserDownload, w io.Writer) (int64, error)
- type CloudBrowserLinkedService
- type CloudBrowserMonitoringOptions
- type CompressionFormat
- type ConcurrentScrapeResult
- type ConfigData
- type ContextData
- type Cookie
- type CostContext
- type CostDetail
- type Crawl
- func (c *Crawl) Cancel() error
- func (c *Crawl) Contents(format CrawlerContentFormat, opts *CrawlContentsOptions) (*CrawlerContents, error)
- func (c *Crawl) Extract(prompt string, schema map[string]interface{}, opts *CrawlExtractOptions) (*CrawlerExtractResponse, error)
- func (c *Crawl) HAR() (*CrawlerArtifact, error)
- func (c *Crawl) Prompt(prompt string, opts *CrawlPromptOptions, handler CrawlPromptHandler) error
- func (c *Crawl) PromptAnswer(prompt string, opts *CrawlPromptOptions) (*CrawlerPromptAnswer, error)
- func (c *Crawl) Read(targetURL string, format CrawlerContentFormat) (*CrawlContent, error)
- func (c *Crawl) ReadBatch(urls []string, formats []CrawlerContentFormat) (map[string]map[string]string, error)
- func (c *Crawl) ReadString(targetURL string, format CrawlerContentFormat) (string, error)
- func (c *Crawl) RefreshHistory(limit int) ([]CrawlerRefreshEntry, error)
- func (c *Crawl) RefreshNow() (*CrawlerRefreshState, error)
- func (c *Crawl) RefreshSettings(settings CrawlRefreshSettings) (*CrawlerRefreshState, error)
- func (c *Crawl) Search(query string, opts *CrawlSearchOptions) (*CrawlerSearchResponse, error)
- func (c *Crawl) Start() error
- func (c *Crawl) Started() bool
- func (c *Crawl) Status(refresh bool) (*CrawlerStatus, error)
- func (c *Crawl) URLs(opts *CrawlURLsOptions) (*CrawlerURLs, error)
- func (c *Crawl) UUID() string
- func (c *Crawl) WARC() (*CrawlerArtifact, error)
- func (c *Crawl) Wait(opts *WaitOptions) error
- type CrawlContent
- type CrawlContentsOptions
- type CrawlExtractOptions
- type CrawlPromptHandler
- type CrawlPromptOptions
- type CrawlRefreshSettings
- type CrawlSearchOptions
- type CrawlURLsOptions
- type CrawlerArtifact
- type CrawlerArtifactType
- type CrawlerConfig
- type CrawlerContentFormat
- type CrawlerContents
- type CrawlerContentsLinks
- type CrawlerExtractResponse
- type CrawlerLifecycleWebhook
- type CrawlerPromptAnswer
- type CrawlerPromptDone
- type CrawlerPromptEvent
- type CrawlerPromptEventType
- type CrawlerPromptSearch
- type CrawlerPromptSource
- type CrawlerRefreshEntry
- type CrawlerRefreshState
- type CrawlerSearchCrawl
- type CrawlerSearchMode
- type CrawlerSearchResponse
- type CrawlerSearchResult
- type CrawlerSearchScores
- type CrawlerSearchSkipped
- type CrawlerSearchState
- type CrawlerSearchStats
- type CrawlerStartResponse
- type CrawlerState
- type CrawlerStatus
- type CrawlerURLDiscoveredWebhook
- type CrawlerURLEntry
- type CrawlerURLFailedWebhook
- type CrawlerURLSkippedWebhook
- type CrawlerURLVisitedWebhook
- type CrawlerURLs
- type CrawlerUpdatedWebhook
- type CrawlerWebhookCommon
- type CrawlerWebhookEvent
- type CreateScheduleRequest
- type DebugContext
- type Enumerable
- type ExtractionConfig
- type ExtractionModel
- type ExtractionResult
- type Format
- type FormatOption
- type HarArchive
- func (a *HarArchive) Creator() map[string]interface{}
- func (a *HarArchive) Entries() []*HarEntry
- func (a *HarArchive) FilterByContentType(contentType string) []*HarEntry
- func (a *HarArchive) FilterByStatus(statusCode int) []*HarEntry
- func (a *HarArchive) FindByURL(url string) *HarEntry
- func (a *HarArchive) IterEntries(fn func(*HarEntry) bool)
- func (a *HarArchive) Len() int
- func (a *HarArchive) Pages() []map[string]interface{}
- func (a *HarArchive) URLs() []string
- func (a *HarArchive) Version() string
- type HarEntry
- func (e *HarEntry) Content() []byte
- func (e *HarEntry) ContentSize() int
- func (e *HarEntry) ContentType() string
- func (e *HarEntry) Method() string
- func (e *HarEntry) RequestHeaders() map[string]string
- func (e *HarEntry) ResponseHeaders() map[string]string
- func (e *HarEntry) StartedDateTime() string
- func (e *HarEntry) StatusCode() int
- func (e *HarEntry) StatusText() string
- func (e *HarEntry) String() string
- func (e *HarEntry) Time() float64
- func (e *HarEntry) Timings() map[string]float64
- func (e *HarEntry) URL() string
- type HttpMethod
- type IFrame
- type ListSchedulesOptions
- type LogLevel
- type Logger
- type MonitoringAggregation
- type MonitoringDataFormat
- type MonitoringMetricsOptions
- type MonitoringPeriod
- type MonitoringTargetMetricsOptions
- type NetworkPolicy
- type OSContext
- type PlaywrightCDPSession
- type Project
- type ProxyContext
- type ProxyPool
- type ResultData
- type RodCaller
- type Schedule
- type ScheduleEnd
- type ScheduleRecurrence
- type ScheduleUsage
- type ScrapeConfig
- type ScrapeResult
- type ScrapeUsage
- type Screenshot
- type ScreenshotConfig
- type ScreenshotFlag
- type ScreenshotFormat
- type ScreenshotMetadata
- type ScreenshotOption
- type ScreenshotResult
- type SpiderUsage
- type Subscription
- type SubscriptionBilling
- type SubscriptionFloatPrice
- type SubscriptionIntegerPrice
- type SubscriptionPeriod
- type SubscriptionUsage
- type URIContext
- type UnblockConfig
- type UnblockResult
- type UpdateScheduleRequest
- type VerifyAPIKeyResult
- type VisionDeficiencyType
- type WaitOptions
- type WarcPage
- type WarcParser
- type WarcRecord
Examples ¶
Constants ¶
const ( // DefaultDownloadChunkSize is the base64 characters read per IO.read: an // 8 MiB message carrying 6 MiB of the file. DefaultDownloadChunkSize = 8 * 1024 * 1024 // MaxDownloadChunkSize is the largest chunk the Cloud Browser serves per IO.read. MaxDownloadChunkSize = 32 * 1024 * 1024 )
const ( CrawlerStatusPending = "PENDING" CrawlerStatusRunning = "RUNNING" CrawlerStatusDone = "DONE" CrawlerStatusCancelled = "CANCELLED" )
Crawler status values returned by GET /crawl/{uuid}/status.
Note: there is no "COMPLETED" or "FAILED" status — a finished crawl is always status=DONE, and success vs. failure is signaled by is_success. CANCELLED is a separate terminal state set when the user cancels the job.
const ( CrawlerStopBacklogEmpty = "backlog_empty" CrawlerStopRetryBacklogOnly = "retry_backlog_only" CrawlerStopNoMoreURLs = "no_more_urls" CrawlerStopPageLimit = "page_limit" CrawlerStopMaxDurationReached = "max_duration_reached" CrawlerStopMaxAPICredit = "max_api_credit" CrawlerStopSeedURLFailed = "seed_url_failed" CrawlerStopUserCancelled = "user_cancelled" CrawlerStopCrawlerError = "crawler_error" CrawlerStopTargetNotAllowed = "target_not_allowed" CrawlerStopWebhookNotFound = "webhook_not_found" CrawlerStopStorageError = "storage_error" CrawlerStopRemoteListFetchFailed = "remote_list_fetch_failed" CrawlerStopRemoteListTooLarge = "remote_list_too_large" CrawlerStopWorkerInterrupted = "worker_interrupted" CrawlerStopInternalError = "internal_error" )
Documented values for CrawlerState.StopReason.
CrawlerStopBacklogEmpty and CrawlerStopRetryBacklogOnly are a normal completion: every URL found was crawled, or only URLs waiting for a retry were left. A stop on a limit (CrawlerStopPageLimit, CrawlerStopMaxDurationReached, CrawlerStopMaxAPICredit) or on CrawlerStopCrawlerError after at least one visited page keeps its pages and ends with is_success true: a stop on CrawlerStopMaxAPICredit is a success.
const ( CrawlerSearchDisabled = "DISABLED" CrawlerSearchBuilding = "BUILDING" CrawlerSearchReady = "READY" CrawlerSearchPartial = "PARTIAL" CrawlerSearchFailed = "FAILED" )
Search index states carried by CrawlerSearchState.Status. Only READY and PARTIAL can answer a query.
const ( CrawlerSkipSearchNotEnabled = "search_not_enabled" CrawlerSkipSearchNotReady = "search_not_ready" CrawlerSkipSearchFailed = "search_failed" CrawlerSkipSearchDisabled = "search_disabled" CrawlerSkipIncompatibleIndex = "incompatible_index" CrawlerSkipDeadline = "deadline" )
Skip reasons reported per crawl in CrawlerSearchResponse.Skipped.
const ( CrawlerRefreshMinInterval = 3600 CrawlerRefreshMaxInterval = 90 * 24 * 3600 )
Refresh interval bounds, in seconds. The floor decides the cost: a crawl refreshing every minute re-scrapes the whole site 1,440 times a day.
const ( CrawlerRefreshDisabled = "DISABLED" CrawlerRefreshScheduled = "SCHEDULED" CrawlerRefreshRunning = "RUNNING" CrawlerRefreshFailed = "FAILED" )
Refresh states carried by CrawlerRefreshState.Status.
const CrawlerStopMaxDuration = "max_duration"
CrawlerStopMaxDuration is the former name of CrawlerStopMaxDurationReached.
Deprecated: the API never returns it; a stop on max_duration is CrawlerStopMaxDurationReached.
const CrawlerStopNoAPICreditLeft = "no_api_credit_left"
CrawlerStopNoAPICreditLeft is a stop reason the API never returns.
Deprecated: the API never returns it.
const CrawlerStopWorkerInterruptedLegacy = "worker_interupted"
CrawlerStopWorkerInterruptedLegacy is the misspelled value that crawls stored before the correction still report.
Deprecated: use CrawlerStopWorkerInterrupted for new crawls.
Variables ¶
var ( // ErrBadAPIKey indicates an invalid or empty API key was provided. ErrBadAPIKey = errors.New("invalid key, must be a non-empty string") // ErrScrapeConfig indicates invalid scrape configuration. ErrScrapeConfig = errors.New("invalid scrape config") // ErrScreenshotConfig indicates invalid screenshot configuration. ErrScreenshotConfig = errors.New("invalid screenshot config") // ErrExtractionConfig indicates invalid extraction configuration. ErrExtractionConfig = errors.New("invalid extraction config") // ErrVNCNotConfigured indicates a Cloud Browser config that carries // neither of the two fields the server salts the VNC credential from. ErrVNCNotConfigured = errors.New("EnableVNC and VNCPassword must both be set on the config") // ErrContentType indicates an invalid content type for the requested operation. ErrContentType = errors.New("invalid content type for this operation") // ErrTooManyRequests indicates rate limiting is in effect. ErrTooManyRequests = errors.New("too many requests") // ErrQuotaLimitReached indicates the account quota has been exceeded. ErrQuotaLimitReached = errors.New("quota limit reached") // ErrScreenshotAPIFailed indicates a screenshot API error occurred. ErrScreenshotAPIFailed = errors.New("screenshot API error") // ErrExtractionAPIFailed indicates an extraction API error occurred. ErrExtractionAPIFailed = errors.New("extraction API error") // ErrUpstreamClient indicates a 4xx error from the target website. ErrUpstreamClient = errors.New("upstream http client error") // ErrUpstreamServer indicates a 5xx error from the target website. ErrUpstreamServer = errors.New("upstream http server error") // ErrAPIClient indicates a 4xx error from the Scrapfly API. ErrAPIClient = errors.New("API http client error") // ErrAPIServer indicates a 5xx error from the Scrapfly API. ErrAPIServer = errors.New("API http server error") // ErrScrapeFailed indicates the scraping operation failed. ErrScrapeFailed = errors.New("scrape failed") // ErrProxyFailed indicates a proxy connection error. ErrProxyFailed = errors.New("proxy error") // ErrASPBypassFailed indicates Anti-Scraping Protection bypass failed. // // The name is frozen: the API reports this as ERR::ASP::* and existing // callers match on this identifier. ErrUnblockerBypassFailed is the same // value under the current name. ErrASPBypassFailed = errors.New("ASP bypass error") // ErrUnblockerBypassFailed indicates the unblocker (formerly "ASP") failed // to bypass the target's anti-bot protection. // // It is the SAME error value as ErrASPBypassFailed, not a second sentinel, // so errors.Is matches either name against the same wrapped error. ErrUnblockerBypassFailed = ErrASPBypassFailed // ErrScheduleFailed indicates a scheduled job error. ErrScheduleFailed = errors.New("schedule error") // ErrWebhookFailed indicates a webhook delivery error. ErrWebhookFailed = errors.New("webhook error") // ErrSessionFailed indicates a browser session error. ErrSessionFailed = errors.New("session error") // ErrUnhandledAPIResponse indicates an unexpected API error response. ErrUnhandledAPIResponse = errors.New("unhandled API error response") // ErrCrawlerConfig indicates invalid crawler configuration. ErrCrawlerConfig = errors.New("invalid crawler config") // ErrCrawlerFailed indicates a crawler API error (e.g. ERR::CRAWLER::*). ErrCrawlerFailed = errors.New("crawler error") // ErrCrawlerNotStarted indicates Crawl helper methods were called before Start(). ErrCrawlerNotStarted = errors.New("crawler not started, call Start() first") // ErrCrawlerAlreadyStarted indicates Crawl.Start() was called twice. ErrCrawlerAlreadyStarted = errors.New("crawler already started") // ErrCrawlerTimeout indicates Crawl.Wait() exceeded the caller's deadline. ErrCrawlerTimeout = errors.New("crawler wait timed out") // ErrCrawlerCancelled indicates Crawl.Wait() observed a CANCELLED terminal state. ErrCrawlerCancelled = errors.New("crawler was cancelled") // ErrUnexpectedResponseFormat indicates the server returned a Content-Type the SDK didn't expect. // Used for example when GET /crawl/{uuid}/urls returns JSON instead of streaming text. ErrUnexpectedResponseFormat = errors.New("unexpected response format") )
Sentinel errors for the Scrapfly client. These errors can be used with errors.Is() for error checking.
var DefaultLogger = NewLogger("scrapfly")
DefaultLogger is the default logger used by the Scrapfly SDK.
You can configure the log level to control verbosity:
scrapfly.DefaultLogger.SetLevel(scrapfly.LevelDebug)
var ErrDownloadIncomplete = errors.New("download stream ended with the wrong size")
ErrDownloadIncomplete reports a stream that ended with fewer or more bytes than the download's size.
Functions ¶
func BoolPtr ¶
BoolPtr is a tiny helper for constructing *bool tri-state fields.
config := &scrapfly.CrawlerConfig{
URL: "https://web-scraping.dev",
RespectRobotsTxt: scrapfly.BoolPtr(false),
FollowInternalSubdomains: scrapfly.BoolPtr(true),
}
func GetAnyEnumFor ¶
func GetAnyEnumFor[V Enumerable[T], T fmt.Stringer]() []any
func GetEnumFor ¶
func GetEnumFor[V Enumerable[T], T fmt.Stringer]() []T
func IsValidEnumType ¶
func ProjectSalt ¶ added in v1.3.0
ProjectSalt returns the deterministic project salt for an api key (sha256(apiKey)[:8]). The Cloud Browser service returns the same value as the X-Browser-Project-Salt response header on VNC-enabled upgrades, where the salt is also the VNC password prefix (<salt>-<password>).
func ValidateAlertCreate ¶ added in v1.3.0
func ValidateAlertCreate(req AlertCreateRequest) error
ValidateAlertCreate runs the same checks the API performs server-side. Use it to fail fast before the network round-trip. It does NOT validate that the MetricID exists in the registry — for that, call ListAlertMetricFamilies first.
Returns nil on success or an error whose Error() string is the same shape the API would have returned (ERR::ALERT::* prefix + reason).
func ValidateEnums ¶
func ValidateEnums(s interface{}) error
ValidateEnums checks fields tagged with `validate:"enum"`. It calls the IsValid() bool method on the field if it's a single value, or on each element if it's a slice.
func ValidateExclusiveFields ¶
func ValidateExclusiveFields(s interface{}) error
ValidateExclusiveFields checks a struct for fields marked with the "exclusive" tag and ensures that only one field per exclusive group is set.
func ValidateRequiredFields ¶
func ValidateRequiredFields(s interface{}) error
ValidateRequiredFields checks a struct for fields with the `required:"true"` tag and returns an error if any of them are zero-valued.
Types ¶
type APIError ¶
type APIError struct {
// Message is the human-readable error message.
Message string
// Code is the error code identifier.
Code string
// HTTPStatusCode is the HTTP status code of the response.
HTTPStatusCode int
// Retryable indicates whether the caller should retry this request.
Retryable bool
// DocumentationURL provides a link to relevant documentation.
DocumentationURL string
// APIResponse contains the full API response (if available).
APIResponse *ScrapeResult
// RetryAfterMs indicates how long to wait before retrying (for rate limits).
RetryAfterMs int
// Hint provides additional context or suggestions for resolving the error.
Hint string
}
APIError represents a detailed error returned by the Scrapfly API.
It contains information about the error including status codes, error messages, documentation links, and retry information.
type APIErrorDetails ¶
type APIErrorDetails struct {
Code string `json:"code"`
HTTPCode int `json:"http_code"`
Links map[string]string `json:"links"`
Message string `json:"message"`
Retryable bool `json:"retryable"`
DocURL string `json:"doc_url"`
}
APIErrorDetails contains detailed error information from the API.
type Account ¶
type Account struct {
AccountID string `json:"account_id"`
Currency string `json:"currency"`
Timezone string `json:"timezone"`
Suspended bool `json:"suspended"`
SuspensionReason string `json:"suspension_reason"`
}
--- Account Data Structures ---
type AccountData ¶
type AccountData struct {
Account Account `json:"account"`
Project Project `json:"project"`
Subscription Subscription `json:"subscription"`
}
AccountData represents detailed account information from Scrapfly.
This includes subscription details, usage statistics, billing information, and account limits.
type Alert ¶ added in v1.3.0
type Alert struct {
UUID string `json:"alert_uuid"`
ProjectUUID string `json:"project_uuid"`
ProjectName string `json:"project_name"`
UserUUID string `json:"user_uuid"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Enabled bool `json:"enabled"`
HmacKey string `json:"hmac_key"`
MetricID string `json:"metric_id"`
MetricDimensions json.RawMessage `json:"metric_dimensions"`
Comparator AlertComparator `json:"comparator"`
Threshold float64 `json:"threshold"`
SustainedMinutes int `json:"sustained_minutes"`
RecoveryMinutes int `json:"recovery_minutes"`
EvaluationWindowM int `json:"evaluation_window_m"`
EvalCadenceSeconds int `json:"eval_cadence_seconds"`
NotifyChannels []AlertNotifyChannel `json:"notify_channels"`
RenotifyMinutes int `json:"renotify_minutes"`
NoDataPolicy AlertNoDataPolicy `json:"no_data_policy"`
State AlertState `json:"state"`
StateSince time.Time `json:"state_since"`
LastNotifiedAt *time.Time `json:"last_notified_at,omitempty"`
LastEvaluatedAt *time.Time `json:"last_evaluated_at,omitempty"`
LastMetricValue *float64 `json:"last_metric_value,omitempty"`
SnoozedUntil *time.Time `json:"snoozed_until,omitempty"`
NotificationsToday int `json:"notifications_today"`
ScheduleUUID *string `json:"schedule_uuid,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Alert is the full alert definition as the API returns it. Pointer fields are nullable in the response — nil means "never set" for last_notified_at, last_evaluated_at, last_metric_value, snoozed_until, schedule_uuid.
HmacKey is the per-alert HMAC-SHA256 signing secret used to authenticate webhook deliveries. Auto-generated on Create; read it from this struct to configure your webhook verifier.
type AlertComparator ¶ added in v1.3.0
type AlertComparator string
AlertComparator is the threshold comparison operator. These are the only operators the API accepts; it rejects any other string with ERR::ALERT::INVALID_THRESHOLD.
const ( AlertComparatorGt AlertComparator = "gt" AlertComparatorLt AlertComparator = "lt" AlertComparatorGte AlertComparator = "gte" AlertComparatorLte AlertComparator = "lte" AlertComparatorEq AlertComparator = "eq" AlertComparatorNeq AlertComparator = "neq" )
type AlertCountActiveResult ¶ added in v1.3.0
type AlertCountActiveResult struct {
Count int `json:"count"`
}
AlertCountActiveResult is the response from CountActiveAlerts — the count of alerts currently in actively-firing states (triggered, pending, recovering). Backs the sidebar badge in the dashboard.
type AlertCreateRequest ¶ added in v1.3.0
type AlertCreateRequest struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
ProjectUUID string `json:"project_uuid,omitempty"`
ProjectName string `json:"project_name,omitempty"`
MetricID string `json:"metric_id"`
MetricDimensions json.RawMessage `json:"metric_dimensions,omitempty"`
Comparator AlertComparator `json:"comparator"`
Threshold float64 `json:"threshold"`
SustainedMinutes int `json:"sustained_minutes,omitempty"`
RecoveryMinutes int `json:"recovery_minutes,omitempty"`
EvaluationWindowM int `json:"evaluation_window_m,omitempty"`
EvalCadenceSeconds int `json:"eval_cadence_seconds,omitempty"`
NotifyChannels []AlertNotifyChannel `json:"notify_channels"`
RenotifyMinutes int `json:"renotify_minutes,omitempty"`
NoDataPolicy AlertNoDataPolicy `json:"no_data_policy,omitempty"`
}
AlertCreateRequest is the body for CreateAlert. The alert binds to the project of the API key, the only project a key creates in: leave ProjectUUID empty (another project is refused) and ProjectName is ignored.
Server-side defaults applied when zero values are sent:
- EvalCadenceSeconds: 300
- SustainedMinutes: metric family default (or 5)
- EvaluationWindowM: SustainedMinutes
- NoDataPolicy: ignore
- RenotifyMinutes: 60
ValidateAlertCreate runs the same checks the API enforces — call it before sending the request to fail fast on the client.
type AlertDeleteResult ¶ added in v1.3.0
type AlertDeleteResult struct {
Deleted string `json:"deleted"`
}
AlertDeleteResult is the response from DeleteAlert.
type AlertListOptions ¶ added in v1.3.0
type AlertListOptions struct {
ProjectUUID string
State AlertState
MetricID string
}
AlertListOptions narrows ListAlerts. Empty fields are omitted from the query string — pass an empty struct to get every alert of the API key's project. ProjectUUID can only name that project: another one lists none.
type AlertMetricFamily ¶ added in v1.3.0
type AlertMetricFamily struct {
ID string `json:"id"`
DisplayName string `json:"display_name"`
Description string `json:"description"`
Unit string `json:"unit"`
Product string `json:"product"`
SourceTable string `json:"source_table"`
Expression string `json:"expression"`
BucketGrainMinutes int `json:"bucket_grain_minutes"`
AllowedDimensions []string `json:"allowed_dimensions"`
TagDimensions map[string]string `json:"tag_dimensions,omitempty"`
DefaultSustainedMinutes int `json:"default_sustained_minutes"`
TimeColumn string `json:"time_column"`
ProjectColumn string `json:"project_column"`
}
AlertMetricFamily is one entry in the metric registry. The dashboard's create wizard renders the metric picker from this list; SDK callers use it to discover legal MetricID values and their allowed dimensions before issuing CreateAlert.
type AlertNoDataPolicy ¶ added in v1.3.0
type AlertNoDataPolicy string
AlertNoDataPolicy controls what to do when the underlying metrics rollup returns no rows in the evaluation window. Mirrors NoDataPolicy in the API.
const ( AlertNoDataOK AlertNoDataPolicy = "ok" AlertNoDataTriggered AlertNoDataPolicy = "triggered" AlertNoDataIgnore AlertNoDataPolicy = "ignore" )
type AlertNotifyChannel ¶ added in v1.3.0
type AlertNotifyChannel struct {
Kind AlertNotifyKind `json:"kind"`
Target string `json:"target"`
Opts map[string]string `json:"opts,omitempty"`
}
AlertNotifyChannel is a single configured delivery target on an alert. Target is the email address, webhook URL, or empty string for inapp. Opts carries channel-specific settings (e.g. custom webhook headers).
type AlertNotifyKind ¶ added in v1.3.0
type AlertNotifyKind string
AlertNotifyKind is the delivery channel for an alert notification. Mirrors NotifyKind in the API.
const ( AlertChannelEmail AlertNotifyKind = "email" AlertChannelWebhook AlertNotifyKind = "webhook" AlertChannelInApp AlertNotifyKind = "inapp" )
type AlertPreviewFiredMarker ¶ added in v1.3.0
type AlertPreviewFiredMarker struct {
FiredAt time.Time `json:"fired_at"`
ResolvedAt *time.Time `json:"resolved_at,omitempty"`
PeakValue float64 `json:"peak_value"`
}
AlertPreviewFiredMarker identifies a TRIGGERED window discovered during a historical preview replay. ResolvedAt is nil when the rule was still firing at the end of the preview range.
type AlertPreviewRequest ¶ added in v1.3.0
type AlertPreviewRequest struct {
MetricID string `json:"metric_id"`
MetricDimensions json.RawMessage `json:"metric_dimensions,omitempty"`
ProjectUUID string `json:"project_uuid,omitempty"`
ProjectName string `json:"project_name,omitempty"`
Comparator AlertComparator `json:"comparator"`
Threshold float64 `json:"threshold"`
SustainedMinutes int `json:"sustained_minutes,omitempty"`
// EvaluationWindowM matches the live evaluator's window; defaults to
// SustainedMinutes server-side when zero.
EvaluationWindowM int `json:"evaluation_window_m,omitempty"`
RangeMinutes int `json:"range_minutes,omitempty"` // default 1440 (24h)
NoDataPolicy AlertNoDataPolicy `json:"no_data_policy,omitempty"`
}
AlertPreviewRequest replays an unsaved rule against historical metric data without persisting anything. Use it to answer "how many times would this rule have fired in the last 24h?" before hitting Create.
type AlertPreviewResponse ¶ added in v1.3.0
type AlertPreviewResponse struct {
Points []AlertSeriesPoint `json:"points"`
Threshold float64 `json:"threshold"`
Comparator AlertComparator `json:"comparator"`
Unit string `json:"unit"`
BucketMinutes int `json:"bucket_minutes"`
FiredCount int `json:"fired_count"`
Markers []AlertPreviewFiredMarker `json:"markers"`
}
AlertPreviewResponse is the payload returned by PreviewAlert. FiredCount is len(Markers) — kept as an explicit field so callers can surface the headline number without iterating.
type AlertSeriesPoint ¶ added in v1.3.0
AlertSeriesPoint is a single (time, value) pair in the metric series returned by GetAlertSeries / PreviewAlert.
type AlertSeriesResponse ¶ added in v1.3.0
type AlertSeriesResponse struct {
Points []AlertSeriesPoint `json:"points"`
Threshold float64 `json:"threshold"`
Comparator AlertComparator `json:"comparator"`
Transitions []AlertTransitionMarker `json:"transitions"`
Unit string `json:"unit"`
MetricID string `json:"metric_id"`
BucketMinutes int `json:"bucket_minutes"`
}
AlertSeriesResponse is the payload returned by GetAlertSeries — everything a chart needs to plot the metric with the threshold band and state-change transitions overlaid.
type AlertSnoozeRequest ¶ added in v1.3.0
type AlertSnoozeRequest struct {
Minutes int `json:"minutes,omitempty"`
UntilResolved bool `json:"until_resolved,omitempty"`
}
AlertSnoozeRequest is the body for SnoozeAlert. Set Minutes for a time-bound snooze, OR UntilResolved=true to mute indefinitely until the next OK transition. Exactly one MUST be provided.
type AlertState ¶ added in v1.3.0
type AlertState string
AlertState is the lifecycle state of an alert definition. These are the only states the API reports.
const ( AlertStateOK AlertState = "ok" AlertStatePending AlertState = "pending" AlertStateTriggered AlertState = "triggered" AlertStateRecovering AlertState = "recovering" AlertStateNoData AlertState = "no_data" AlertStateSnoozed AlertState = "snoozed" )
type AlertTestResult ¶ added in v1.3.0
type AlertTestResult struct {
OK bool `json:"ok"`
AlertUUID string `json:"alert_uuid"`
Channels int `json:"channels"`
EventID string `json:"event_id"`
}
AlertTestResult is the response from TestAlert — a synthetic notification fired on every configured channel without touching alert state.
type AlertTransitionMarker ¶ added in v1.3.0
type AlertTransitionMarker struct {
T time.Time `json:"t"`
From AlertState `json:"from"`
To AlertState `json:"to"`
}
AlertTransitionMarker is a state-change event overlaid on the graph.
type AlertUpdateRequest ¶ added in v1.3.0
type AlertUpdateRequest struct {
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
Comparator *AlertComparator `json:"comparator,omitempty"`
Threshold *float64 `json:"threshold,omitempty"`
SustainedMinutes *int `json:"sustained_minutes,omitempty"`
RecoveryMinutes *int `json:"recovery_minutes,omitempty"`
EvaluationWindowM *int `json:"evaluation_window_m,omitempty"`
NotifyChannels []AlertNotifyChannel `json:"notify_channels,omitempty"`
RenotifyMinutes *int `json:"renotify_minutes,omitempty"`
NoDataPolicy *AlertNoDataPolicy `json:"no_data_policy,omitempty"`
}
AlertUpdateRequest is the body for UpdateAlert. All fields are pointers so the caller can distinguish "omit" from "set to zero" — only non-nil fields are applied server-side. Each successful update auto-snoozes the alert for SustainedMinutes so a tuning iteration doesn't refire on the next eval tick.
type Attachment ¶
type Attachment struct {
Content string `json:"content"`
ContentType string `json:"content_type"`
Filename string `json:"filename"`
ID string `json:"id"`
Size int `json:"size"`
State string `json:"state"`
SuggestedFilename string `json:"suggested_filename"`
URL string `json:"url"`
// contains filtered or unexported fields
}
func (*Attachment) Data ¶
func (a *Attachment) Data() ([]byte, error)
Data returns the attachment data as a byte slice.
func (*Attachment) Save ¶
func (a *Attachment) Save(savePath ...string) (string, error)
Save saves a scraped attachment result to disk.
Parameters:
- savePath: Optional directory path where to save the file (defaults to current directory) (if savePath does not exists, it will be created in a best effort basis)
it is named as the filename of the attachment Returns the full path to the saved file.
Example:
filePath, err := a.Save("./attachments")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Attachment %s saved to: %s\n", a.Filename, filePath)
type BatchFormat ¶ added in v0.3.3
type BatchFormat int
BatchFormat selects the per-part body encoding on the wire. JSON is the default; Msgpack produces slightly smaller payloads and matches the Scrapfly API's msgpack negotiation used by the Python SDK.
const ( BatchFormatJSON BatchFormat = iota BatchFormatMsgpack )
type BatchOptions ¶ added in v0.3.3
type BatchOptions struct {
Format BatchFormat
}
BatchOptions carries optional knobs for ScrapeBatchWithOptions. Zero value = JSON parts (default), same as the simple ScrapeBatch.
type BatchResult ¶ added in v0.3.3
type BatchResult struct {
CorrelationID string
Result *ScrapeResult
ProxifiedResponse *http.Response
Err error
}
BatchResult wraps a single scrape's outcome within a batch response. Exactly one of Result, ProxifiedResponse, or Err is non-nil. CorrelationID matches the value the caller set on the originating ScrapeConfig.
ProxifiedResponse is populated when the originating ScrapeConfig had ProxyResponse=true — the batch part's body is the raw upstream response (HTML, JSON, binary, etc.) and Upstream response headers / status are available on the *http.Response. This mirrors the single-scrape Scrape() → ScrapeProxified() split.
type BrowserData ¶
type BrowserData struct {
JSEvaluationResult *string `json:"javascript_evaluation_result"`
JSScenario interface{} `json:"js_scenario"`
LocalStorageData map[string]interface{} `json:"local_storage_data"`
SessionStorageData map[string]interface{} `json:"session_storage_data"`
Websockets []interface{} `json:"websockets"`
XHRCall []interface{} `json:"xhr_call"`
Attachments []Attachment `json:"attachments"`
}
BrowserData contains data collected from the browser during JavaScript rendering.
type BrowserDownload ¶ added in v1.8.0
BrowserDownload is one file of the session's download directory. A small file carries its base64 content in Data. A large one, with DownloadsStream, carries the IO handle to read in Stream instead, and its size in bytes in Size.
func ParseDownloads ¶ added in v1.8.0
func ParseDownloads(raw json.RawMessage) ([]BrowserDownload, error)
ParseDownloads reads a ScrapiumBrowser.getDownloads result, in either of its shapes, sorted by name.
func (BrowserDownload) Streamed ¶ added in v1.8.0
func (d BrowserDownload) Streamed() bool
Streamed reports whether the download is read through an IO stream handle.
type CDPSender ¶ added in v1.8.0
type CDPSender interface {
SendCDP(ctx context.Context, method string, params map[string]any) (json.RawMessage, error)
}
CDPSender sends one CDP command on a Cloud Browser session and returns its result.
func ChromedpCDP ¶ added in v1.8.0
func ChromedpCDP(executor ChromedpExecutor) CDPSender
ChromedpCDP sends through chromedp: pass chromedp.FromContext(ctx).Target.
func PlaywrightCDP ¶ added in v1.8.0
func PlaywrightCDP(session PlaywrightCDPSession) CDPSender
PlaywrightCDP sends through playwright-go: pass context.NewCDPSession(page). playwright-go takes no context, so a cancelled ctx only stops between commands.
type CDPSenderFunc ¶ added in v1.8.0
type CDPSenderFunc func(ctx context.Context, method string, params map[string]any) (json.RawMessage, error)
CDPSenderFunc adapts a function to CDPSender, for a CDP client of your own.
type CacheContext ¶
type CacheContext struct {
State string `json:"state"`
Entry interface{} `json:"entry"`
}
CacheContext contains information about cache usage for the request.
type ChromedpExecutor ¶ added in v1.8.0
type ChromedpExecutor interface {
Execute(ctx context.Context, method string, params, res any) error
}
ChromedpExecutor is the method set of chromedp's *chromedp.Target (cdp.Executor, chromedp v0.10 and later).
type ClassifyRequest ¶ added in v0.3.3
type ClassifyRequest struct {
URL string `json:"url"`
StatusCode int `json:"status_code"`
Headers map[string]string `json:"headers,omitempty"`
Body string `json:"body,omitempty"`
Method string `json:"method,omitempty"`
}
ClassifyRequest describes an HTTP response the caller wants the Scrapfly classification engine to evaluate for blocking signals.
type ClassifyResult ¶ added in v0.3.3
type ClassifyResult struct {
Blocked bool `json:"blocked"`
Antibot string `json:"antibot,omitempty"`
Cost int `json:"cost"`
}
ClassifyResult is the response from /classify.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the main client for interacting with the Scrapfly API. It handles authentication, request execution, and response parsing.
func New ¶
New creates a new Scrapfly client with the provided API key. The API key can be obtained from https://scrapfly.io/dashboard.
Example:
client, err := scrapfly.New("YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
func NewWithHost ¶
NewWithHost creates a new Scrapfly client with a custom API host. This is useful for enterprise deployments or testing against a custom endpoint.
Parameters:
- key: Your Scrapfly API key
- host: Custom API host URL (e.g., "https://api.web-scraping.dev")
- verifySSL: Whether to verify SSL certificates (set to false only for testing)
Example:
client, err := scrapfly.NewWithHost("YOUR_API_KEY", "https://api.web-scraping.dev", true)
func (*Client) Account ¶
func (c *Client) Account() (*AccountData, error)
Account retrieves information about the current Scrapfly account.
Returns account details including:
- Subscription plan and limits
- API usage statistics
- Billing information
- Concurrency limits
Example:
account, err := client.Account()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Plan: %s\n", account.Subscription.PlanName)
fmt.Printf("Remaining requests: %d\n", account.Subscription.Usage.Scrape.Remaining)
func (*Client) CancelSchedule ¶ added in v0.3.4
func (*Client) Classify ¶ added in v0.3.3
func (c *Client) Classify(ctx context.Context, req *ClassifyRequest) (*ClassifyResult, error)
Classify asks the Scrapfly classification endpoint whether the given response looks blocked by an anti-bot product. Unlike Scrape, this does not fetch anything — the response body is supplied by the caller. 1 API credit per call. See https://scrapfly.io/docs/scrape-api/classify for the full contract.
func (*Client) CloudBrowser ¶
func (c *Client) CloudBrowser(config *CloudBrowserConfig) string
CloudBrowser returns the Cloud Browser WebSocket connection URL.
On rejection the server sends a JSON error frame then a close frame with code 1008/1011/1013 and a "ERR::BROWSER::CODE: reason" string. See https://scrapfly.io/docs/cloud-browser-api/errors#websocket-close-frame
func (*Client) CloudBrowserExtensionDelete ¶
CloudBrowserExtensionDelete deletes a browser extension by ID.
func (*Client) CloudBrowserExtensionGet ¶
CloudBrowserExtensionGet returns details of a specific extension.
func (*Client) CloudBrowserExtensionList ¶
CloudBrowserExtensionList lists all browser extensions for the account.
func (*Client) CloudBrowserExtensionUpload ¶
CloudBrowserExtensionUpload uploads a browser extension from a local .zip or .crx file.
func (*Client) CloudBrowserPlayback ¶
CloudBrowserPlayback returns debug recording metadata for a given run ID. The response carries `available`, `status` (one of `ready`, `uploading`, `unavailable`, `disabled`), `metadata`, `video_url`, and `retry_after_ms`.
func (*Client) CloudBrowserProjectSalt ¶ added in v1.3.0
CloudBrowserProjectSalt returns the project salt for this client's api key.
func (*Client) CloudBrowserSessionStop ¶
CloudBrowserSessionStop terminates a browser session.
func (*Client) CloudBrowserSessions ¶
CloudBrowserSessions lists all running Cloud Browser sessions.
func (*Client) CloudBrowserUnblock ¶
func (c *Client) CloudBrowserUnblock(config UnblockConfig) (*UnblockResult, error)
CloudBrowserUnblock bypasses anti-bot protection and returns a WebSocket URL to a browser with cookies/state pre-loaded.
func (*Client) CloudBrowserVNCPassword ¶ added in v1.5.0
func (c *Client) CloudBrowserVNCPassword(config *CloudBrowserConfig) (string, error)
CloudBrowserVNCPassword returns the password a native VNC client must type to attach to a session created with config, using this client's api key.
func (*Client) CloudBrowserVaultCreate ¶ added in v1.3.0
CloudBrowserVaultCreate creates a new credential vault.
The response includes a freshly minted base64 32-byte vault key under the `key` field. The server emits this exactly once — callers MUST store it locally. It is required for any subsequent item read/write or for vault rotation.
func (*Client) CloudBrowserVaultDelete ¶ added in v1.3.0
CloudBrowserVaultDelete removes a vault and every item it holds. Cannot be reversed.
func (*Client) CloudBrowserVaultGet ¶ added in v1.3.0
CloudBrowserVaultGet returns the metadata for one vault. No secret material is included in the response.
func (*Client) CloudBrowserVaultItemCreate ¶ added in v1.3.0
func (c *Client) CloudBrowserVaultItemCreate(vaultID, vaultKey string, item map[string]interface{}) (map[string]interface{}, error)
CloudBrowserVaultItemCreate adds a credential to a vault. The item payload follows the controller's typed shape:
map[string]interface{}{
"type": "password",
"label": "web-scraping.dev test",
"origin": "https://web-scraping.dev/password-manager-test",
"username": "user123",
"secret": map[string]interface{}{"password": "password"},
}
vaultKey is forwarded as the X-Vault-Key header. Treat it as secret material — the SDK will not log it.
func (*Client) CloudBrowserVaultItemDelete ¶ added in v1.3.0
func (c *Client) CloudBrowserVaultItemDelete(vaultID, itemID string) (map[string]interface{}, error)
CloudBrowserVaultItemDelete removes a single item from a vault. No vault key is required — the row is dropped without decryption.
func (*Client) CloudBrowserVaultItemList ¶ added in v1.3.0
CloudBrowserVaultItemList returns every item in a vault.
The server returns metadata + the envelope-encrypted secret_blob — plaintext secrets are not exposed by this endpoint and never reach the SDK. To read plaintext, the dashboard performs WebCrypto on the blob locally with the customer-held vault key.
func (*Client) CloudBrowserVaultItemUpdate ¶ added in v1.3.0
func (c *Client) CloudBrowserVaultItemUpdate(vaultID, itemID, vaultKey string, patch map[string]interface{}) (map[string]interface{}, error)
CloudBrowserVaultItemUpdate patches a vault item.
Pass vaultKey only when the patch includes secret rotation — i.e. a non-nil "secret" key in `patch`. For metadata-only patches (label, origin, username), pass an empty string and the X-Vault-Key header is not sent.
func (*Client) CloudBrowserVaultList ¶ added in v1.3.0
CloudBrowserVaultList returns every vault visible to the API key in the current project + environment. Response shape: {vaults: [...]}.
func (*Client) CloudBrowserVaultRotate ¶ added in v1.3.0
func (c *Client) CloudBrowserVaultRotate(vaultID, currentVaultKey string) (map[string]interface{}, error)
CloudBrowserVaultRotate rotates the vault key. The OLD key MUST be supplied as currentVaultKey — the API uses it to decrypt every item and rewraps each per-row DEK under a freshly generated key, returned exactly once in the `key` field of the response. After this call the old key cannot read any item in the vault.
currentVaultKey is forwarded as the X-Vault-Key header. It is NEVER logged, included in error messages, or echoed back via Recorder breadcrumbs — see the security contract at the top of this section.
func (*Client) CloudBrowserVaultServiceLink ¶ added in v1.7.0
func (c *Client) CloudBrowserVaultServiceLink(vaultID, vaultKey string, linkedService CloudBrowserLinkedService, token string, serviceData map[string]interface{}) (map[string]interface{}, error)
CloudBrowserVaultServiceLink links a manual vault to an external secret manager and turns it into a mirror. linkedService is required: this route has no server-side default, so LinkedServiceUnset is rejected.
serviceData carries the non-secret selection rules; vault_id or vault_name is required, the rest are optional:
map[string]interface{}{
"vault_name": "scrapfly-ci",
"title_filter": "prod-*",
"tags": []string{"scrapfly"},
"sync_mode": "on_session", // or "manual"
"sync_ttl_s": 900,
}
token is the provider's service-account token. vaultKey is mandatory here because the token is sealed under it and the server verifies the key first: a well-formed wrong key would link the vault and leave a token every later sync fails to open. Both are secret material — the SDK does not log either.
A vault that is already linked, or that still holds rows owned by a service, is refused (409).
func (*Client) CloudBrowserVaultServiceSync ¶ added in v1.7.0
func (c *Client) CloudBrowserVaultServiceSync(vaultID, vaultKey string) (map[string]interface{}, error)
CloudBrowserVaultServiceSync forces a provider fetch and reconcile now, bypassing the sync TTL and the hour-long back-off a failed run leaves behind. The response is the flat report — imported, updated, deleted, skipped, unmirrored, status, warnings.
vaultKey is required: the sealed service-account token is opened with it, and the server verifies the key before claiming the sync round.
The server budget is 25s. This call runs under the client-wide timeout (160s, see New / NewWithHost), so a slow provider still returns the server's own report instead of a client-side cancel.
func (*Client) CloudBrowserVaultServiceTest ¶ added in v1.7.0
func (c *Client) CloudBrowserVaultServiceTest(vaultID, vaultKey string, linkedService CloudBrowserLinkedService, token string) (map[string]interface{}, error)
CloudBrowserVaultServiceTest probes provider credentials without reading any secret: the response is {vaults_visible, item_count, warnings}, which is what fills an upstream-vault picker.
linkedService and token are both optional. Pass a candidate token to probe before a link exists — the probe then ignores the stored selection rules and reports every vault the token can reach, and a LinkedServiceUnset discriminator is defaulted server-side. Pass LinkedServiceUnset and an empty token to probe with the token already sealed in the vault, which therefore has to be linked. vaultKey is always required: it is what opens that sealed token.
Nothing is sent as a body when both fields are empty, so an empty probe cannot be read as a request to test an empty token.
The server budget is 10s, inside the client-wide timeout.
func (*Client) CloudBrowserVaultServiceUnlink ¶ added in v1.7.0
func (c *Client) CloudBrowserVaultServiceUnlink(vaultID string, keepItems bool) (map[string]interface{}, error)
CloudBrowserVaultServiceUnlink drops the link and turns the vault back into a manual one.
keepItems governs the mirrored rows only — the sealed service-account token is deleted either way. keepItems=false cannot be undone, which is why the server keeps the items when the flag is absent or unparseable; the SDK always writes the flag explicitly so an omission on the wire never decides it. No vault key: nothing is sealed or opened.
func (*Client) CloudBrowserVaultServiceUpdate ¶ added in v1.7.0
func (c *Client) CloudBrowserVaultServiceUpdate(vaultID, vaultKey, token string, serviceData map[string]interface{}) (map[string]interface{}, error)
CloudBrowserVaultServiceUpdate patches an existing link. serviceData replaces the stored selection document wholesale — send the whole document, not a delta.
Pass token only to rotate the service-account token; vaultKey is then required, the same way CloudBrowserVaultItemUpdate requires it for a secret rotation. For a metadata-only update pass both as "" and no X-Vault-Key header is sent.
linkedService is not a parameter: the server re-decodes against the vault's stored discriminator, so a link's provider cannot be switched in place — unlink and link again.
func (*Client) CloudBrowserVaultUpdate ¶ added in v1.3.0
func (c *Client) CloudBrowserVaultUpdate(vaultID string, name, description string) (map[string]interface{}, error)
CloudBrowserVaultUpdate patches a vault's metadata. Empty-string args are treated as "no change" and omitted from the wire payload — pass only the fields you want to overwrite.
func (*Client) CloudBrowserVideo ¶
CloudBrowserVideo downloads a debug session recording video. Returns the raw video bytes (webm format).
func (*Client) CloudBrowserWaitForPlayback ¶ added in v1.3.0
func (c *Client) CloudBrowserWaitForPlayback(runID string, timeout, fallbackInterval time.Duration) (map[string]interface{}, error)
CloudBrowserWaitForPlayback polls the playback endpoint until the recording resolves to a terminal state (`ready` or `unavailable`) or the timeout elapses. It honours the server's `retry_after_ms` hint when present, and falls back to fallbackInterval otherwise. Pass timeout == 0 to fall back to 3 minutes; fallbackInterval == 0 falls back to 3 seconds.
func (*Client) ConcurrentScrape ¶
func (c *Client) ConcurrentScrape(configs []*ScrapeConfig, concurrencyLimit int) <-chan ConcurrentScrapeResult
if item.Error != nil {
log.Printf("Error: %v", item.Error)
continue
}
fmt.Println(item.Result.Result.Content)
}
func (*Client) CountActiveAlerts ¶ added in v1.3.0
func (c *Client) CountActiveAlerts(projectUUID string) (*AlertCountActiveResult, error)
CountActiveAlerts returns the count of alerts currently in actively- firing states (triggered, pending, recovering) for the API key's project. Cheap — designed for sub-millisecond badge rendering in the dashboard. projectUUID is optional and can only name that project.
func (*Client) CrawlArtifact ¶
func (c *Client) CrawlArtifact(uuid string, artifactType CrawlerArtifactType) (*CrawlerArtifact, error)
CrawlArtifact downloads a crawler job's WARC or HAR artifact.
`GET /crawl/{uuid}/artifact?type=warc|har` — returns raw bytes wrapped in a CrawlerArtifact. The SDK does NOT bundle WARC/HAR parsers; use a library like nlnwa/gowarc to walk the records.
The download waits at least 300s; a longer client Timeout, or none, is kept.
func (*Client) CrawlCancel ¶
CrawlCancel cancels a running crawler job.
`POST /crawl/{uuid}/cancel` — proxied through to the crawler backend's internal cancel endpoint after the API verifies job ownership. Calling cancel on a job that has already finished (DONE/CANCELLED) is a no-op.
Returns nil on success. Wraps any `ERR::CRAWLER::*` response with ErrCrawlerFailed so callers can switch on errors.Is().
func (*Client) CrawlContentsBatch ¶
func (c *Client) CrawlContentsBatch(uuid string, urls []string, formats []CrawlerContentFormat) (map[string]map[string]string, error)
CrawlContentsBatch retrieves content for up to 100 URLs in a single round-trip. Returns a map of url → format → content.
`POST /crawl/{uuid}/contents/batch` — the request body is a newline- separated list of URLs (text/plain). The response is a multipart/related (RFC 2387) document with one part per found URL.
Formats may be any subset of the documented content formats. Each returned URL will have an inner map with only the formats the server found.
func (*Client) CrawlContentsJSON ¶
func (c *Client) CrawlContentsJSON(uuid string, format CrawlerContentFormat, opts *CrawlContentsOptions) (*CrawlerContents, error)
CrawlContents fetches crawled content for a job.
Two modes (selected by Plain):
- Bulk JSON (Plain=false, default): returns *CrawlerContents with a {contents: {url: {format: content}}, links} envelope.
- Plain single-URL (Plain=true): returns a string containing the raw content for the given URL/format. Requires URL to be set.
Returns either (*CrawlerContents, nil) or ("plain string", nil). Callers should type-assert on the interface{} return. Go's lack of sum types makes this awkward — use CrawlContentsJSON or CrawlContentsPlain directly when you know which mode you want.
Example:
contents, err := client.CrawlContentsJSON(uuid, scrapfly.CrawlerFormatMarkdown, nil) md, err := client.CrawlContentsPlain(uuid, "https://web-scraping.dev/page", scrapfly.CrawlerFormatMarkdown)
func (*Client) CrawlContentsPlain ¶
func (c *Client) CrawlContentsPlain(uuid, targetURL string, format CrawlerContentFormat) (string, error)
CrawlContentsPlain fetches the raw content for a single crawled URL in "plain" mode. Returns the body as a string (no JSON wrapping).
The Accept header is set to `*/*` since the server picks the content-type based on the format (text/markdown, text/html, text/plain, application/json).
func (*Client) CrawlExtract ¶ added in v1.7.0
func (c *Client) CrawlExtract(uuid, prompt string, schema map[string]interface{}, opts *CrawlExtractOptions) (*CrawlerExtractResponse, error)
CrawlExtract extracts a structured object from a single crawl's content.
func (*Client) CrawlPrompt ¶ added in v1.6.0
func (c *Client) CrawlPrompt(uuid, prompt string, opts *CrawlPromptOptions, handler CrawlPromptHandler) error
CrawlPrompt answers a question from a single crawl's content.
func (*Client) CrawlPromptAnswer ¶ added in v1.7.0
func (c *Client) CrawlPromptAnswer(uuid, prompt string, opts *CrawlPromptOptions) (*CrawlerPromptAnswer, error)
CrawlPromptAnswer answers a question from a single crawl's content, all at once.
func (*Client) CrawlRefreshHistory ¶ added in v1.6.0
func (c *Client) CrawlRefreshHistory(uuid string, limit int) ([]CrawlerRefreshEntry, error)
CrawlRefreshHistory reads a crawl's refresh timeline, newest last.
`GET /crawl/{uuid}/refresh/history`: the server keeps the 50 most recent runs; older rows are trimmed rather than paged, because the timeline exists to show recent activity. Pass limit 0 for everything the server kept.
func (*Client) CrawlRefreshNow ¶ added in v1.6.0
func (c *Client) CrawlRefreshNow(uuid string) (*CrawlerRefreshState, error)
CrawlRefreshNow runs one refresh of an existing crawl immediately, without waiting for the next scheduled period.
`POST /crawl/{uuid}/refresh` re-scrapes the crawl's own URLs in place: same crawler UUID, same artifacts, same search index. Only pages whose content actually changed are re-indexed, and pages that disappeared are dropped, so everything already pointing at this crawl keeps working.
A refresh bills the pages it re-scrapes, exactly like the original crawl. What unchanged pages save is the embedding and the index write.
This call is NOT retried on failure: a retry would start a second re-scrape of the whole site, and that is billable.
func (*Client) CrawlRefreshSettings ¶ added in v1.6.0
func (c *Client) CrawlRefreshSettings(uuid string, settings CrawlRefreshSettings) (*CrawlerRefreshState, error)
CrawlRefreshSettings changes the refresh schedule of an existing crawl.
`PATCH /crawl/{uuid}/refresh`: only the fields set on settings are changed. Turning refresh on for a crawl started without it is allowed: the crawl already holds the URL index a refresh walks.
func (*Client) CrawlSearch ¶ added in v1.6.0
func (c *Client) CrawlSearch(uuid, query string, opts *CrawlSearchOptions) (*CrawlerSearchResponse, error)
CrawlSearch searches a single crawl's index.
`GET /crawl/{uuid}/search` is the documented convenience path; this SDK reaches the same implementation through the collection endpoint so single and multi-crawl search cannot answer differently.
func (*Client) CrawlStatus ¶
func (c *Client) CrawlStatus(uuid string) (*CrawlerStatus, error)
CrawlStatus fetches the current status of a crawler job.
`GET /crawl/{uuid}/status` — returns a strictly-validated CrawlerStatus. The caller can use IsRunning/IsComplete/IsFailed/IsCancelled to check state transitions.
func (*Client) CrawlURLs ¶
func (c *Client) CrawlURLs(uuid string, opts *CrawlURLsOptions) (*CrawlerURLs, error)
CrawlURLs lists crawled URLs for a job, streaming the response as text.
`GET /crawl/{uuid}/urls` — the server returns `text/plain` with one record per line. JSON is intentionally NOT used: this endpoint is expected to scale to millions of records per job where JSON would be too expensive.
Wire format:
- `visited` / `pending` → one URL per line
- `failed` / `skipped` → `url,reason` per line
Pagination: the wire protocol carries no global total count. Request further pages by incrementing Page until an empty response.
func (*Client) CrawlsExtract ¶ added in v1.7.0
func (c *Client) CrawlsExtract(crawlIDs []string, prompt string, schema map[string]interface{}, opts *CrawlExtractOptions) (*CrawlerExtractResponse, error)
CrawlsExtract extracts a structured object from the content of one or more crawls.
`POST /crawl/extract` retrieves like CrawlsPromptAnswer and answers with Data shaped by schema, a JSON Schema handed to the model as its response schema. There is no streaming variant. CrawlExtract is sugar over a one-element list.
No retry: a retry re-runs the fan-out and the generation.
Example:
res, err := client.CrawlsExtract([]string{uuid}, "Every product with its price", map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{"products": map[string]interface{}{"type": "array"}},
"required": []string{"products"},
}, nil)
var out struct{ Products []struct{ Name string; Price float64 } }
err = res.Decode(&out)
func (*Client) CrawlsPrompt ¶ added in v1.6.0
func (c *Client) CrawlsPrompt(crawlIDs []string, prompt string, opts *CrawlPromptOptions, handler CrawlPromptHandler) error
CrawlsPrompt answers a question from the content of one or more crawls, streaming the answer as it is generated.
`POST /crawl/prompt`: the collection endpoint is the real API, and CrawlPrompt is sugar over a one-element list.
Frames arrive as sources, then tokens, then one done frame; the handler is called for each. An `event: error` frame is not delivered to the handler: it is returned as an error wrapping ErrCrawlerFailed, which can happen after tokens have already been handed over, since generation fails mid-stream.
No retry: the request runs a fan-out and a generation, both billable, and replaying it doubles the bill. fetchWithRetry is deliberately not used here.
Example:
err := client.CrawlsPrompt([]string{uuid}, "Summarize the pricing page", nil,
func(ev scrapfly.CrawlerPromptEvent) error {
if ev.Type == scrapfly.CrawlerPromptEventToken {
fmt.Print(ev.Token)
}
return nil
})
func (*Client) CrawlsPromptAnswer ¶ added in v1.7.0
func (c *Client) CrawlsPromptAnswer(crawlIDs []string, prompt string, opts *CrawlPromptOptions) (*CrawlerPromptAnswer, error)
CrawlsPromptAnswer answers a question from the content of one or more crawls, and returns the whole answer once generation completes.
`POST /crawl/prompt` with `generation.stream: false`: the same facts as the frames CrawlsPrompt hands its handler. CrawlPromptAnswer is sugar over a one-element list.
No retry: the request runs a fan-out and a generation, both billable.
func (*Client) CrawlsSearch ¶ added in v1.6.0
func (c *Client) CrawlsSearch(crawlIDs []string, query string, opts *CrawlSearchOptions) (*CrawlerSearchResponse, error)
CrawlsSearch searches the indexes of one or more crawls and returns one merged ranking.
`POST /crawl/search`: the collection endpoint is the real API, and CrawlSearch is sugar over a one-element list so the two cannot drift.
Only crawls started with Search=true whose index reached READY or PARTIAL contribute. The rest come back in Skipped with a reason and never fail the call, so always inspect Skipped before concluding a crawl had no match.
Example:
res, err := client.CrawlsSearch([]string{uuidA, uuidB}, "TLS fingerprint",
&scrapfly.CrawlSearchOptions{Limit: 20, Mode: scrapfly.CrawlerSearchModeHybrid})
for _, hit := range res.Results {
fmt.Printf("%d. %s (%.3f)\n", hit.Rank, hit.URL, hit.Score)
}
func (*Client) CreateAlert ¶ added in v1.3.0
func (c *Client) CreateAlert(req AlertCreateRequest) (*Alert, error)
CreateAlert persists a new alert definition. The returned Alert carries the server-assigned UUID, the auto-generated HMAC signing key, and the resolved server-side defaults for any zero-value fields in the request.
Calling ValidateAlertCreate(req) first is recommended — it runs the same checks server-side, so a successful local validation avoids one network round-trip per bad payload.
func (*Client) CreateCrawlerSchedule ¶ added in v0.3.4
func (c *Client) CreateCrawlerSchedule(crawlerConfig map[string]interface{}, req *CreateScheduleRequest) (*Schedule, error)
CreateCrawlerSchedule creates a Crawler API schedule.
crawlerConfig is forwarded verbatim and its keys are WIRE keys, not the CrawlerConfig field names. As with CreateScrapeSchedule, the anti-bot bypass may be spelled "asp" or "unblocker": the API folds the alias into "asp" on the stored config before it is ever replayed.
func (*Client) CreateScrapeSchedule ¶ added in v0.3.4
func (c *Client) CreateScrapeSchedule(scrapeConfig map[string]interface{}, req *CreateScheduleRequest) (*Schedule, error)
CreateScrapeSchedule creates a Web Scraping API schedule.
scrapeConfig is forwarded to the API verbatim, so its keys are WIRE keys and not the ScrapeConfig field names — e.g. "render_js", not "RenderJS". The anti-bot bypass may be spelled either way here: the API folds "unblocker" into "asp" on the STORED config, with the same precedence the SDK uses (a supplied "asp" wins; "unblocker" is read only when "asp" is absent, null or ""), so both names reach the replayed scrape.
func (*Client) CreateScreenshotSchedule ¶ added in v0.3.4
func (c *Client) CreateScreenshotSchedule(screenshotConfig map[string]interface{}, req *CreateScheduleRequest) (*Schedule, error)
func (*Client) DeleteAlert ¶ added in v1.3.0
func (c *Client) DeleteAlert(alertUUID string) (*AlertDeleteResult, error)
DeleteAlert removes an alert definition. Returns {"deleted": "<uuid>"}. Idempotent on the happy path; calling twice for the same UUID returns 404 (ERR::ALERT::NOT_FOUND) on the second call.
func (*Client) ExecuteSchedule ¶ added in v0.3.4
func (*Client) Extract ¶
func (c *Client) Extract(config *ExtractionConfig) (*ExtractionResult, error)
Extract performs AI-powered structured data extraction from HTML content.
This method uses Scrapfly's AI extraction capabilities to parse HTML and extract structured data based on templates or prompts.
The request waits at least 165s; a longer client Timeout, or none, is kept.
Example:
config := &scrapfly.ExtractionConfig{
Body: []byte("<html>...</html>"),
ContentType: "text/html",
ExtractionTemplate: "product",
}
result, err := client.Extract(config)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Extracted data: %+v\n", result.Data)
func (*Client) GetAlert ¶ added in v1.3.0
GetAlert fetches one alert definition by UUID.
Returns an *APIError with HTTPStatusCode 404 (Code ERR::ALERT::NOT_FOUND) for both "doesn't exist" and "not yours" — the API deliberately collapses these to prevent enumeration. Don't try to distinguish them.
func (*Client) GetAlertSeries ¶ added in v1.3.0
func (c *Client) GetAlertSeries(alertUUID string, rangeMinutes int) (*AlertSeriesResponse, error)
GetAlertSeries returns the time-series metric data + state-change transitions for an alert. rangeMinutes is the lookback window (default 240 = 4h; max 7*24*60 = 10080 = 7 days). Values outside that bound are silently clamped to the default by the API.
func (*Client) GetBrowserMonitoringMetrics ¶ added in v0.3.0
func (c *Client) GetBrowserMonitoringMetrics(opts CloudBrowserMonitoringOptions) (map[string]any, error)
func (*Client) GetBrowserMonitoringTimeseries ¶ added in v0.3.0
func (c *Client) GetBrowserMonitoringTimeseries(opts CloudBrowserMonitoringOptions) (map[string]any, error)
func (*Client) GetCrawlerMonitoringMetrics ¶ added in v0.3.0
func (c *Client) GetCrawlerMonitoringMetrics(opts MonitoringMetricsOptions) (map[string]any, error)
func (*Client) GetCrawlerMonitoringTargetMetrics ¶ added in v0.3.0
func (c *Client) GetCrawlerMonitoringTargetMetrics(opts MonitoringTargetMetricsOptions) (map[string]any, error)
func (*Client) GetExtractionMonitoringMetrics ¶ added in v0.3.0
func (c *Client) GetExtractionMonitoringMetrics(opts MonitoringMetricsOptions) (map[string]any, error)
func (*Client) GetExtractionMonitoringTargetMetrics ¶ added in v0.3.0
func (c *Client) GetExtractionMonitoringTargetMetrics(opts MonitoringTargetMetricsOptions) (map[string]any, error)
func (*Client) GetMonitoringMetrics ¶ added in v0.3.0
func (c *Client) GetMonitoringMetrics(opts MonitoringMetricsOptions) (map[string]any, error)
func (*Client) GetMonitoringTargetMetrics ¶ added in v0.3.0
func (c *Client) GetMonitoringTargetMetrics(opts MonitoringTargetMetricsOptions) (map[string]any, error)
func (*Client) GetSchedule ¶ added in v0.3.4
func (*Client) GetScreenshotMonitoringMetrics ¶ added in v0.3.0
func (c *Client) GetScreenshotMonitoringMetrics(opts MonitoringMetricsOptions) (map[string]any, error)
func (*Client) GetScreenshotMonitoringTargetMetrics ¶ added in v0.3.0
func (c *Client) GetScreenshotMonitoringTargetMetrics(opts MonitoringTargetMetricsOptions) (map[string]any, error)
func (*Client) HTTPClient ¶
HTTPClient returns the *http.Client used by this Scrapfly client. Useful if callers want to wrap the existing transport instead of replacing it.
func (*Client) ListAlertMetricFamilies ¶ added in v1.3.0
func (c *Client) ListAlertMetricFamilies() ([]AlertMetricFamily, error)
ListAlertMetricFamilies returns the full metric registry (~19 entries at the time of writing). Use it to discover legal MetricID values before issuing CreateAlert, and to discover each metric's allowed dimensions and native bucket grain.
func (*Client) ListAlerts ¶ added in v1.3.0
func (c *Client) ListAlerts(opts AlertListOptions) ([]Alert, error)
ListAlerts returns the alert definitions of the API key's project. Filters in opts narrow the result server-side — pass an empty AlertListOptions{} to get all of them.
Example:
alerts, err := client.ListAlerts(scrapfly.AlertListOptions{
State: scrapfly.AlertStateTriggered,
})
func (*Client) ListCrawlerSchedules ¶ added in v0.3.4
func (c *Client) ListCrawlerSchedules(opts *ListSchedulesOptions) ([]Schedule, error)
func (*Client) ListSchedules ¶ added in v0.3.4
func (c *Client) ListSchedules(opts *ListSchedulesOptions) ([]Schedule, error)
func (*Client) ListScrapeSchedules ¶ added in v0.3.4
func (c *Client) ListScrapeSchedules(opts *ListSchedulesOptions) ([]Schedule, error)
func (*Client) ListScreenshotSchedules ¶ added in v0.3.4
func (c *Client) ListScreenshotSchedules(opts *ListSchedulesOptions) ([]Schedule, error)
func (*Client) PauseSchedule ¶ added in v0.3.4
func (*Client) PreviewAlert ¶ added in v1.3.0
func (c *Client) PreviewAlert(req AlertPreviewRequest) (*AlertPreviewResponse, error)
PreviewAlert replays an unsaved rule against historical data and returns "would-have-fired" markers — without creating the alert. Useful for tuning thresholds before committing.
func (*Client) ResumeSchedule ¶ added in v0.3.4
func (*Client) Scrape ¶
func (c *Client) Scrape(config *ScrapeConfig) (*ScrapeResult, error)
Scrape performs a web scraping request using the provided configuration. This is the main method for scraping web pages with Scrapfly.
The method supports various features including:
- JavaScript rendering (RenderJS)
- Proxy rotation and geo-targeting
- Anti-bot protection bypass (Unblocker)
- Custom headers and cookies
- Screenshot capture
- Data extraction
Example:
config := &scrapfly.ScrapeConfig{
URL: "https://web-scraping.dev",
Country: "us",
Unblocker: scrapfly.BoolPtr(true),
}
result, err := client.Scrape(config)
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Result.Content)
func (*Client) ScrapeBatch ¶ added in v0.3.3
func (c *Client) ScrapeBatch(configs []*ScrapeConfig) (<-chan BatchResult, error)
ScrapeBatch issues a POST /scrape/batch request with up to 100 configs and streams per-scrape results through the returned channel as each scrape completes. Results arrive OUT OF ORDER — match them back to their originating config via CorrelationID.
Every ScrapeConfig MUST carry a unique CorrelationID. Missing / duplicate values are caught client-side before the request is sent, so callers fail fast on misconfiguration.
The returned channel is closed when the last part has been delivered (or the stream ends due to error). Block on receive.
For msgpack wire encoding use ScrapeBatchWithOptions.
func (*Client) ScrapeBatchWithOptions ¶ added in v0.3.3
func (c *Client) ScrapeBatchWithOptions(configs []*ScrapeConfig, opts BatchOptions) (<-chan BatchResult, error)
ScrapeBatchWithOptions is ScrapeBatch with explicit BatchOptions (e.g. msgpack per-part encoding).
func (*Client) ScrapeProxified ¶
func (c *Client) ScrapeProxified(config *ScrapeConfig) (*http.Response, error)
ConcurrentScrape performs multiple scraping requests concurrently with controlled concurrency. This is useful for scraping multiple pages efficiently while respecting rate limits.
Parameters:
- configs: A slice of ScrapeConfig objects to scrape
- concurrencyLimit: Maximum number of concurrent requests. If <= 0, uses account's concurrent limit
Returns a channel that emits ConcurrentScrapeResult values as scrapes complete. Each entry has either Result (success) or Error (failure) set.
Example:
configs := []*scrapfly.ScrapeConfig{
{URL: "https://web-scraping.dev/page1"},
{URL: "https://web-scraping.dev/page2"},
{URL: "https://web-scraping.dev/page3"},
}
for item := range client.ConcurrentScrape(configs, 3) {
ScrapeProxified sends a scrape request with proxified_response=true and returns the raw upstream *http.Response. The caller owns resp.Body (must Close() it).
Unlike Scrape(), no JSON parsing occurs — the response body is the target page's raw content, the status code is the upstream status, and Scrapfly metadata is available on X-Scrapfly-* response headers (Api-Cost, Content-Format, Log, etc).
Use this when you want Scrapfly to act like an HTTP proxy and your code already knows how to handle raw HTTP responses.
func (*Client) Screenshot ¶
func (c *Client) Screenshot(config *ScreenshotConfig) (*ScreenshotResult, error)
Screenshot captures a screenshot of a web page using the provided configuration.
Supports various features including:
- Multiple image formats (JPG, PNG, WEBP, GIF)
- Full page or element-specific capture
- Custom resolution
- Dark mode
- Banner blocking
Example:
config := &scrapfly.ScreenshotConfig{
URL: "https://web-scraping.dev",
Format: scrapfly.FormatPNG,
Capture: "fullpage",
Resolution: "1920x1080",
}
result, err := client.Screenshot(config)
if err != nil {
log.Fatal(err)
}
// result.Image contains the screenshot bytes
func (*Client) SetAPIKey ¶
SetAPIKey updates the API key for the client. This is useful for switching between different API keys at runtime.
func (*Client) SetCloudBrowserHost ¶
SetCloudBrowserHost overrides the default Cloud Browser host (wss://browser.scrapfly.io). Useful for self-hosted or development environments. When unset, CloudBrowser methods fall back to the public production host.
func (*Client) SetHTTPClient ¶
SetHTTPClient replaces the underlying *http.Client used for all API calls. This lets callers install a custom transport (e.g. for request logging, tracing, tests, or a shared connection pool).
Its Timeout applies to every API call of the Client, except that Extract waits at least 165s, CrawlArtifact 300s, and CrawlsPrompt, CrawlsPromptAnswer and CrawlsExtract, with their single-crawl forms, 180s. A longer Timeout, or none, is kept for those calls too.
Passing nil is a no-op.
Example — install a RoundTripper that logs every request:
client, _ := scrapfly.New("YOUR_API_KEY")
client.SetHTTPClient(&http.Client{
Transport: &loggingTransport{base: http.DefaultTransport},
Timeout: 160 * time.Second,
})
func (*Client) SnoozeAlert ¶ added in v1.3.0
func (c *Client) SnoozeAlert(alertUUID string, req AlertSnoozeRequest) (*Alert, error)
SnoozeAlert mutes notifications. Provide either Minutes>0 OR UntilResolved=true (not both) — the API rejects neither-or-both with ERR::ALERT::INVALID_SUSTAINED_WINDOW.
func (*Client) StartCrawl ¶
func (c *Client) StartCrawl(config *CrawlerConfig) (*CrawlerStartResponse, error)
StartCrawl schedules a new crawler job and returns the crawler UUID.
This corresponds to `POST /crawl`. The config is serialized as a JSON body (not URL query params like Scrape) because the Crawler API takes a richer structured config. The API key is still sent via the `key` query parameter.
Example:
config := &scrapfly.CrawlerConfig{
URL: "https://web-scraping.dev/products",
PageLimit: 10,
ContentFormats: []scrapfly.CrawlerContentFormat{scrapfly.CrawlerFormatMarkdown},
}
start, err := client.StartCrawl(config)
if err != nil {
log.Fatal(err)
}
fmt.Println("uuid:", start.CrawlerUUID)
func (*Client) TestAlert ¶ added in v1.3.0
func (c *Client) TestAlert(alertUUID string) (*AlertTestResult, error)
TestAlert fires a one-shot synthetic notification on every configured channel WITHOUT touching alert state or the state machine. Useful for verifying webhook URLs and email addresses without waiting for a real transition.
Dedup: two test fires within the same UTC minute share the same dedup key — the second is suppressed and the response carries the same EventID. This is intentional (matches the dashboard's UI rate-limit).
func (*Client) UnsnoozeAlert ¶ added in v1.3.0
UnsnoozeAlert lifts any active snooze, resuming normal notification delivery on the next evaluator tick.
func (*Client) UpdateAlert ¶ added in v1.3.0
func (c *Client) UpdateAlert(alertUUID string, req AlertUpdateRequest) (*Alert, error)
UpdateAlert patches an existing alert. All AlertUpdateRequest fields are pointers — only non-nil fields are applied. The alert is auto- snoozed for SustainedMinutes after a successful update, preventing notification spam during threshold tuning.
func (*Client) UpdateSchedule ¶ added in v0.3.4
func (c *Client) UpdateSchedule(id string, req *UpdateScheduleRequest) (*Schedule, error)
func (*Client) VerifyAPIKey ¶
func (c *Client) VerifyAPIKey() (*VerifyAPIKeyResult, error)
VerifyAPIKey checks if the configured API key is valid. Returns a VerifyAPIKeyResult indicating whether the key is valid.
Example:
result, err := client.VerifyAPIKey()
if err != nil {
log.Fatal(err)
}
if result.Valid {
fmt.Println("API key is valid")
}
type CloudBrowserConfig ¶
type CloudBrowserConfig struct {
// ProxyPool is "datacenter", "residential", "tor" or "byop".
ProxyPool string `json:"proxy_pool,omitempty"`
// OS is the fingerprint operating system: linux, windows, macos, android, iphone, ipad.
OS string `json:"os,omitempty"`
Country string `json:"country,omitempty"`
// Lang is the browser UI language — the singular navigator.language base
// tag (e.g. "en"). Empty means the server derives it from Country.
Lang string `json:"lang,omitempty"`
// Languages is the ordered language preference list driving
// navigator.languages and the q-weighted Accept-Language header
// (e.g. []string{"fr-FR", "fr", "en-US"}). Sent comma-joined; capped
// server-side at 3 entries.
Languages []string `json:"languages,omitempty"`
Session string `json:"session,omitempty"`
Timeout int `json:"timeout,omitempty"` // Session timeout in seconds (default 900)
BlockImages bool `json:"block_images,omitempty"`
BlockStyles bool `json:"block_styles,omitempty"`
BlockFonts bool `json:"block_fonts,omitempty"`
BlockMedia bool `json:"block_media,omitempty"`
Screenshot bool `json:"screenshot,omitempty"`
Cache bool `json:"cache,omitempty"`
Blacklist bool `json:"blacklist,omitempty"`
Debug bool `json:"debug,omitempty"`
Resolution string `json:"resolution,omitempty"`
Extensions []string `json:"extensions,omitempty"`
BrowserBrand string `json:"browser_brand,omitempty"`
// TargetURL is the URL this session will scrape. It is not navigated to —
// the browser still goes wherever you drive it over CDP — but declaring it
// helps Scrapfly's proxy network route the traffic accordingly and pick the
// fingerprint for that site before the browser starts.
//
// Strongly recommended. Routing is decided once, when the session opens, so
// a session declared without a target cannot be re-routed afterwards.
//
// Must be an absolute URL including the scheme ("https://web-scraping.dev"); a
// bare hostname is rejected server-side and silently leaves the session
// without a declared target.
TargetURL string `json:"target_url,omitempty"`
// NetworkPolicy restricts the hosts this session can reach.
NetworkPolicy *NetworkPolicy `json:"network_policy,omitempty"`
// BYOPProxy is a "Bring Your Own Proxy" URL that the Cloud Browser will use
// instead of Scrapfly's managed proxy pools.
//
// Format: {protocol}://{user}:{pass}@{host}:{port}
// Supported protocols: http, https, socks5, socks5h, socks5+udp, socks5h+udp.
// The +udp variants enable HTTP/3 (QUIC) via SOCKS5 UDP ASSOCIATE — only
// works with proxy providers that implement RFC 1928 UDP ASSOCIATE.
//
// Requires a Custom plan subscription.
// See https://scrapfly.io/docs/cloud-browser-api/byop for details.
BYOPProxy string `json:"byop_proxy,omitempty"`
// EnableMCP enables the Cloud Browser's built-in Model Context Protocol (MCP) support.
// When true, the browser exposes a streamable-HTTP MCP endpoint for AI agents.
EnableMCP bool `json:"enable_mcp,omitempty"`
// SolveCaptcha arms the Cloud Browser's built-in captcha detector + solver on the
// first page attach. Turnstile, DataDome slider, reCAPTCHA, GeeTest,
// PerimeterX hold, and puzzle-click captchas are handled automatically —
// no extra CDP calls from the client.
//
// Billed per solved captcha, at the price of its type (Supported Captcha
// Types in the docs below); a failed attempt (captchaError) costs nothing
// unless the captcha's solve had started.
// See https://scrapfly.io/docs/cloud-browser-api/captcha-solver for details.
SolveCaptcha bool `json:"solve_captcha,omitempty"`
// Vault is the credential vault NAME to attach to the session — the
// alphanumeric name you gave it at create time. The API resolves it to
// the vault scoped to your api-key's project and environment, then
// injects its credentials (passwords, passkeys, cookies, TOTP codes)
// into matching origins via CDP. Pair with VaultKey — the customer-held
// base64 32-byte key the API needs to decrypt the vault for this session
// only. Both land on the wss:// URL as query parameters; the API never
// persists VaultKey.
//
// Treat VaultKey as secret material — never log it.
Vault string `json:"vault,omitempty"`
VaultKey string `json:"vault_key,omitempty"`
// EnableVNC turns on the human-in-the-loop VNC channel (operator attach
// via Scrapfly's VNC mux at :5901).
EnableVNC bool `json:"enable_vnc,omitempty"`
// VNCPassword is the customer-chosen VNC password. Required when
// EnableVNC is true and HITLAllowedNetworks is empty.
VNCPassword string `json:"vnc_password,omitempty"`
// EnableRTC turns on the human-in-the-loop WebRTC channel.
EnableRTC bool `json:"enable_rtc,omitempty"`
// RTCUsername is the WebRTC username. Defaults to "scrapfly" server-side.
RTCUsername string `json:"rtc_username,omitempty"`
// RTCPassword is the customer-chosen WebRTC password. Required when
// EnableRTC is true and HITLAllowedNetworks is empty.
RTCPassword string `json:"rtc_password,omitempty"`
// HITLAllowedNetworks lists source IPs / CIDRs trusted to attach to
// the HITL channels (VNC + WebRTC + downloads) without credentials.
HITLAllowedNetworks []string `json:"hitl_allowed_networks,omitempty"`
// DownloadsStream makes ScrapiumBrowser.getDownloads return large downloaded
// files as IO stream handles instead of inline base64: read them with
// CloudBrowserDownloads. See
// https://scrapfly.io/docs/cloud-browser-api/file-downloads#large-downloads
DownloadsStream bool `json:"downloads_stream,omitempty"`
}
CloudBrowserConfig configures a Cloud Browser session.
func (*CloudBrowserConfig) VNCClientPassword ¶ added in v1.5.0
func (cfg *CloudBrowserConfig) VNCClientPassword(apiKey string) (string, error)
VNCClientPassword returns the password a native VNC client must type to attach to a session created with this config: "<project_salt>-<VNCPassword>".
Required by the VNC TCP endpoint (port 5901), which the server salts at allocation. The WebSocket endpoint /run/<run_id>/vnc takes the raw VNCPassword instead. Returns ErrVNCNotConfigured when the config carries no VNC credential to salt.
type CloudBrowserDownloads ¶ added in v1.8.0
type CloudBrowserDownloads struct {
// ChunkSize is the base64 characters read per IO.read, rounded down to a
// multiple of 4: DefaultDownloadChunkSize when zero, MaxDownloadChunkSize at most.
ChunkSize int
// contains filtered or unexported fields
}
CloudBrowserDownloads reads the downloads of a Cloud Browser session.
func NewCloudBrowserDownloads ¶ added in v1.8.0
func NewCloudBrowserDownloads(sender CDPSender) *CloudBrowserDownloads
NewCloudBrowserDownloads reads downloads through sender: ChromedpCDP, RodCDP, PlaywrightCDP, or a CDPSenderFunc of your own.
func (*CloudBrowserDownloads) List ¶ added in v1.8.0
func (d *CloudBrowserDownloads) List(ctx context.Context) ([]BrowserDownload, error)
List returns every download of the session: small ones with their content, large ones as handles.
func (*CloudBrowserDownloads) Metadata ¶ added in v1.8.0
Metadata returns the size in bytes of every completed download, by filename.
func (*CloudBrowserDownloads) Read ¶ added in v1.8.0
func (d *CloudBrowserDownloads) Read(ctx context.Context, download BrowserDownload) ([]byte, error)
Read returns the whole content of a download, in memory.
func (*CloudBrowserDownloads) Save ¶ added in v1.8.0
func (d *CloudBrowserDownloads) Save(ctx context.Context, download BrowserDownload, path string) (string, error)
Save writes a download to path, a file or a directory (the current one when empty), chunk by chunk, and returns the path written.
func (*CloudBrowserDownloads) SaveAll ¶ added in v1.8.0
SaveAll writes every download of the session into dir and returns their paths.
func (*CloudBrowserDownloads) WaitFor ¶ added in v1.8.0
func (d *CloudBrowserDownloads) WaitFor(ctx context.Context, filename string, interval time.Duration) (int64, error)
WaitFor waits until filename is listed with the same size twice in a row and returns that size, checking every interval (500ms when zero). Bound it with ctx.
func (*CloudBrowserDownloads) WriteTo ¶ added in v1.8.0
func (d *CloudBrowserDownloads) WriteTo(ctx context.Context, download BrowserDownload, w io.Writer) (int64, error)
WriteTo writes the bytes of a download to w, one decoded chunk at a time, and returns how many it wrote. A stream handle is read once and always closed.
type CloudBrowserLinkedService ¶ added in v1.7.0
type CloudBrowserLinkedService string
CloudBrowserLinkedService is the provider discriminator of a linked vault. The server keys its decoder on these values; anything else is refused with 400 and never stored.
const ( // LinkedServiceOnePassword is the only provider the server registers today. LinkedServiceOnePassword CloudBrowserLinkedService = "1password" // LinkedServiceUnset is accepted only by CloudBrowserVaultServiceTest, where // the server picks the provider for a candidate-token probe. POST /service // has no default and rejects it. LinkedServiceUnset CloudBrowserLinkedService = "" )
type CloudBrowserMonitoringOptions ¶ added in v0.3.0
type CloudBrowserMonitoringOptions struct {
Period MonitoringPeriod
// ProxyPool filters to one Cloud Browser pool, as its runs record it:
// datacenter, residential, tor or byop.
ProxyPool string
Start time.Time
End time.Time
}
CloudBrowserMonitoringOptions configures Cloud Browser monitoring queries. Cloud Browser is session-based with a distinct shape from the request-based products (no domain/target, no include_webhook).
type CompressionFormat ¶
type CompressionFormat string
CompressionFormat specifies the compression format for document body.
const ( // GZIP uses gzip compression (widely supported, good compression ratio). GZIP CompressionFormat = "gzip" // ZSTD uses Zstandard compression (better compression and speed than gzip). ZSTD CompressionFormat = "zstd" // DEFLATE uses DEFLATE compression (older format, similar to gzip). DEFLATE CompressionFormat = "deflate" )
Available compression formats for document body compression.
type ConcurrentScrapeResult ¶
type ConcurrentScrapeResult struct {
// Result is the successful scrape, or nil when Error is set.
Result *ScrapeResult
// Error is the failure, or nil when Result is set.
Error error
}
ConcurrentScrapeResult is one entry in the channel returned by ConcurrentScrape. Exactly one of Result and Error is non-nil per emission.
This was previously an anonymous struct with embedded fields, which prevented callers outside package scrapfly from accessing the error (Go's universe-scope `error` type produces an unexported promoted field in anonymous structs). Named exported fields make the result usable from any caller.
type ConfigData ¶
type ConfigData struct {
URL string `json:"url"`
Method string `json:"method"`
Country *string `json:"country"`
RenderJS bool `json:"render_js"`
Cache bool `json:"cache"`
CacheClear bool `json:"cache_clear"`
CacheTTL int `json:"cache_ttl"`
SSL bool `json:"ssl"`
DNS bool `json:"dns"`
ASP bool `json:"asp"`
Debug bool `json:"debug"`
ProxyPool string `json:"proxy_pool"` // the pool the way the account reads it, see ProxyContext.Pool
Session *string `json:"session"`
SessionStickyProxy bool `json:"session_sticky_proxy"`
Tags []string `json:"tags"`
CorrelationID *string `json:"correlation_id"`
// Retry echoes back the retry=true/false flag the caller sent. The server
// may normalize this to a nested object in a future release; for now it's
// a plain bool. Nullable because older API versions omit the field.
Retry *bool `json:"retry,omitempty"`
// BrowserBrand echoes back the browser_brand value the caller sent when
// render_js=true. Nullable because the field is only populated when the
// request actually exercised the browser path.
BrowserBrand *string `json:"browser_brand,omitempty"`
Body *string `json:"body"`
// Headers echoes back the request headers the server actually sent. The
// API serializes each header value as an array (e.g. `{"accept": ["*/*"]}`)
// to preserve HTTP's multi-value semantics, matching Go's stdlib
// http.Header shape. Request-side headers live on ScrapeConfig.Headers
// (plain map[string]string), which the client serializes into the
// `headers[key]=value` query-string form.
Headers map[string][]string `json:"headers"`
JS *string `json:"js"`
RenderingWait int `json:"rendering_wait"`
WaitForSelector *string `json:"wait_for_selector"`
Screenshots map[string]string `json:"screenshots"`
ScreenshotFlags []string `json:"screenshot_flags"`
WebhookName *string `json:"webhook_name"`
Timeout int `json:"timeout"`
JSScenario interface{} `json:"js_scenario"`
Extract interface{} `json:"extract"`
Lang []string `json:"lang"`
OS *string `json:"os"`
AutoScroll bool `json:"auto_scroll"`
CostBudget *int `json:"cost_budget"`
RenderingStage string `json:"rendering_stage"`
Env string `json:"env"`
Origin string `json:"origin"`
Project string `json:"project"`
UserUUID string `json:"user_uuid"`
UUID string `json:"uuid"`
}
ConfigData contains the configuration that was used for a scrape request. This mirrors the 'config' object in the API response.
type ContextData ¶
type ContextData struct {
ASP interface{} `json:"asp"`
BandwidthConsumed int `json:"bandwidth_consumed"`
Cache CacheContext `json:"cache"`
Cookies []Cookie `json:"cookies"`
Cost CostContext `json:"cost"`
CreatedAt string `json:"created_at"`
Debug DebugContext `json:"debug"`
Env string `json:"env"`
//Fingerprint string `json:"fingerprint"`
Fingerprint interface{} `json:"fingerprint"`
Headers map[string]string `json:"headers"`
IsXMLHTTPRequest bool `json:"is_xml_http_request"`
Job interface{} `json:"job"`
Lang interface{} `json:"lang"` // []string or string
OS OSContext `json:"os"`
Project string `json:"project"`
Proxy ProxyContext `json:"proxy"`
Redirects interface{} `json:"redirects"` // []string or string
Retry int `json:"retry"`
Schedule interface{} `json:"schedule"`
Session interface{} `json:"session"`
Spider interface{} `json:"spider"`
Throttler interface{} `json:"throttler"`
URI URIContext `json:"uri"`
URL string `json:"url"`
Webhook interface{} `json:"webhook"`
}
ContextData contains metadata about the scrape request execution. This includes proxy information, costs, cache status, and more.
type Cookie ¶
type Cookie struct {
Name string `json:"name"`
Value string `json:"value"`
Expires string `json:"expires"`
Path string `json:"path"`
Comment string `json:"comment"`
Domain string `json:"domain"`
MaxAge int `json:"max_age"`
Secure bool `json:"secure"`
HTTPOnly bool `json:"http_only"`
Version string `json:"version"`
Size int `json:"size"`
}
Cookie represents an HTTP cookie.
type CostContext ¶
type CostContext struct {
Details []CostDetail `json:"details"`
Total int `json:"total"`
}
CostContext contains the cost breakdown for a scrape request.
type CostDetail ¶
type CostDetail struct {
Amount int `json:"amount"`
Code string `json:"code"`
Description string `json:"description"`
}
CostDetail represents a single cost item for a scrape request.
type Crawl ¶
type Crawl struct {
// contains filtered or unexported fields
}
Crawl is the high-level fluent wrapper around a single crawler job lifecycle.
It tracks the UUID returned by Start() and caches the most recent status and downloaded artifacts. Callers can use it as:
crawl := scrapfly.NewCrawl(client, &scrapfly.CrawlerConfig{
URL: "https://web-scraping.dev/products",
PageLimit: 10,
})
if err := crawl.Start(); err != nil { log.Fatal(err) }
if err := crawl.Wait(nil); err != nil { log.Fatal(err) }
status, _ := crawl.Status(true)
fmt.Println("visited", status.State.URLsVisited)
md, _ := crawl.Read("https://web-scraping.dev/products", scrapfly.CrawlerFormatMarkdown)
fmt.Println(md[:200])
Use the lower-level client methods (Client.StartCrawl, Client.CrawlStatus, etc.) directly if you need finer control, concurrency, or want to avoid the caching behavior.
func NewCrawl ¶
func NewCrawl(client *Client, config *CrawlerConfig) *Crawl
NewCrawl constructs a Crawl wrapper. It does NOT schedule the job — call Start() to actually submit the crawler config to the API.
func (*Crawl) Cancel ¶
Cancel cancels this crawl. Returns nil on success. Calling Cancel on a crawler that has already finished is a server-side no-op (still returns nil).
Mirrors Python SDK's `Crawl.cancel()`.
func (*Crawl) Contents ¶
func (c *Crawl) Contents(format CrawlerContentFormat, opts *CrawlContentsOptions) (*CrawlerContents, error)
Contents returns the bulk JSON envelope for crawled pages.
func (*Crawl) Extract ¶ added in v1.7.0
func (c *Crawl) Extract(prompt string, schema map[string]interface{}, opts *CrawlExtractOptions) (*CrawlerExtractResponse, error)
Extract extracts a structured object from this crawl's content, shaped by schema. Thin wrapper around Client.CrawlExtract.
func (*Crawl) HAR ¶
func (c *Crawl) HAR() (*CrawlerArtifact, error)
HAR downloads the HAR artifact for this crawl (cached after first call).
func (*Crawl) Prompt ¶ added in v1.6.0
func (c *Crawl) Prompt(prompt string, opts *CrawlPromptOptions, handler CrawlPromptHandler) error
Prompt answers a question from this crawl's content, streaming the answer through handler. Thin wrapper around Client.CrawlPrompt.
func (*Crawl) PromptAnswer ¶ added in v1.7.0
func (c *Crawl) PromptAnswer(prompt string, opts *CrawlPromptOptions) (*CrawlerPromptAnswer, error)
PromptAnswer answers a question from this crawl's content, all at once. Thin wrapper around Client.CrawlPromptAnswer.
func (*Crawl) Read ¶
func (c *Crawl) Read(targetURL string, format CrawlerContentFormat) (*CrawlContent, error)
Read fetches the content for a single crawled URL.
Returns a CrawlContent wrapper for parity with the Python SDK's `Crawl.read()`. The wrapper carries the raw content string plus the originating URL and crawler UUID. Status code / headers / duration are not populated by the plain-mode endpoint (those would require fetching the full WARC artifact).
Returns nil if the URL was not part of this crawl (server returns 404).
func (*Crawl) ReadBatch ¶
func (c *Crawl) ReadBatch(urls []string, formats []CrawlerContentFormat) (map[string]map[string]string, error)
ReadBatch retrieves content for up to 100 URLs in one round-trip.
func (*Crawl) ReadString ¶
func (c *Crawl) ReadString(targetURL string, format CrawlerContentFormat) (string, error)
ReadString is a convenience wrapper for callers that just want the raw content string without the CrawlContent envelope. Returns an empty string (and nil error) when the URL isn't part of this crawl.
func (*Crawl) RefreshHistory ¶ added in v1.6.0
func (c *Crawl) RefreshHistory(limit int) ([]CrawlerRefreshEntry, error)
RefreshHistory reads this crawl's refresh timeline, newest last. Thin wrapper around Client.CrawlRefreshHistory.
func (*Crawl) RefreshNow ¶ added in v1.6.0
func (c *Crawl) RefreshNow() (*CrawlerRefreshState, error)
RefreshNow re-scrapes this crawl's URLs in place, right now. Thin wrapper around Client.CrawlRefreshNow.
The crawl keeps its uuid, its artifacts and its search index; only pages whose content changed are re-indexed and pages that disappeared are dropped.
func (*Crawl) RefreshSettings ¶ added in v1.6.0
func (c *Crawl) RefreshSettings(settings CrawlRefreshSettings) (*CrawlerRefreshState, error)
RefreshSettings changes this crawl's refresh schedule. Thin wrapper around Client.CrawlRefreshSettings; only the fields set on settings change.
func (*Crawl) Search ¶ added in v1.6.0
func (c *Crawl) Search(query string, opts *CrawlSearchOptions) (*CrawlerSearchResponse, error)
Search queries this crawl's search index. Thin wrapper around Client.CrawlSearch, which itself goes through the collection endpoint.
Requires the crawl to have been started with CrawlerConfig.Search=true and its index to have reached READY or PARTIAL; poll CrawlerStatus.Search or subscribe to the crawler_search_ready webhook. An index that is not ready yet is reported in the response's Skipped list, not as an error.
func (*Crawl) Start ¶
Start schedules the crawl on the Scrapfly API. Calling it twice returns ErrCrawlerAlreadyStarted.
func (*Crawl) Status ¶
func (c *Crawl) Status(refresh bool) (*CrawlerStatus, error)
Status fetches the current status of the crawler job.
When refresh=true, always hits the API. When refresh=false, returns the most recently cached status (or hits the API on first call). Most callers want refresh=true inside polling loops; set refresh=false when you just need to re-read the last known state cheaply.
func (*Crawl) URLs ¶
func (c *Crawl) URLs(opts *CrawlURLsOptions) (*CrawlerURLs, error)
URLs lists crawled URLs for this crawl. Thin wrapper around Client.CrawlURLs.
func (*Crawl) WARC ¶
func (c *Crawl) WARC() (*CrawlerArtifact, error)
WARC downloads the WARC artifact for this crawl (cached after first call).
func (*Crawl) Wait ¶
func (c *Crawl) Wait(opts *WaitOptions) error
Wait polls Status until the crawler reaches a terminal state.
Returns nil when the crawler reaches DONE with IsSuccess=true. Returns an error wrapping ErrCrawlerFailed / ErrCrawlerCancelled / ErrCrawlerTimeout for the other terminal conditions.
Pass nil for default behavior (5-second polling, no timeout).
type CrawlContent ¶
type CrawlContent struct {
// URL is the crawled URL.
URL string
// Content is the page content in the requested format.
Content string
// StatusCode is the HTTP response status code from the original scrape.
// Zero when the SDK couldn't determine the status (e.g. plain mode
// fetches don't carry the status, only the content).
StatusCode int
// Headers contains the HTTP response headers from the original scrape.
// Empty in plain-mode fetches; populated when the content comes from a
// richer source (e.g. WARC artifact, JSON contents envelope).
Headers map[string]string
// Duration is the original scrape duration in seconds, or zero if unknown.
Duration float64
// LogID is the Scrapfly scrape log ID for debugging, or empty if unknown.
LogID string
// Country is the country the request was made from, or empty if unknown.
Country string
// CrawlUUID is the parent crawler job UUID.
CrawlUUID string
}
CrawlContent is the response object for a single crawled URL fetched via `Crawl.Read(url, format)` or the lower-level `Client.CrawlContentsPlain`.
Mirrors the Python SDK's `CrawlContent` class. Provides typed accessors for the content, status code, headers, and metadata of a single page.
func (*CrawlContent) Error ¶
func (c *CrawlContent) Error() bool
Error reports whether the original scrape was a 4xx/5xx response.
func (*CrawlContent) Len ¶
func (c *CrawlContent) Len() int
Len returns the length of the content string.
func (*CrawlContent) LogURL ¶
func (c *CrawlContent) LogURL() string
LogURL returns the dashboard URL for this scrape's log, or empty if LogID is unset.
func (*CrawlContent) String ¶
func (c *CrawlContent) String() string
String returns the raw content. Lets fmt.Println pretty-print it.
func (*CrawlContent) Success ¶
func (c *CrawlContent) Success() bool
Success reports whether the original scrape was a 2xx response.
type CrawlContentsOptions ¶
type CrawlContentsOptions struct {
// Format selects the content format. Required.
Format CrawlerContentFormat
// URL targets a single crawled URL. Required when Plain=true.
URL string
// Plain=true returns the raw content for a single URL (requires URL) as
// a string with Content-Type matching the format. Default false returns
// the JSON envelope wrapped in CrawlerContents.
Plain bool
// Limit caps the number of URLs in bulk JSON mode (max 50, default 10).
Limit int
// Offset skips N URLs in bulk JSON mode.
Offset int
}
CrawlContentsOptions configures a GET /crawl/{uuid}/contents request.
type CrawlExtractOptions ¶ added in v1.7.0
type CrawlExtractOptions struct {
// Search overrides retrieval. Nil uses the server's defaults.
Search *CrawlSearchOptions
}
CrawlExtractOptions configures an extraction.
type CrawlPromptHandler ¶ added in v1.6.0
type CrawlPromptHandler func(event CrawlerPromptEvent) error
CrawlPromptHandler receives each decoded frame of the prompt stream. Returning a non-nil error stops consumption and is returned to the caller; the connection is closed either way.
type CrawlPromptOptions ¶ added in v1.6.0
type CrawlPromptOptions struct {
// Search overrides retrieval. Nil uses the server's defaults.
Search *CrawlSearchOptions
// Model names the generation model. Empty = server default.
Model string
}
CrawlPromptOptions configures a prompt request.
type CrawlRefreshSettings ¶ added in v1.6.0
CrawlRefreshSettings is the body of a PATCH /crawl/{uuid}/refresh call.
Both fields are pointers so that "leave alone" stays distinguishable from "set to false" / "set to zero": turning a crawl off must keep its interval for when it is turned back on.
type CrawlSearchOptions ¶ added in v1.6.0
type CrawlSearchOptions struct {
// Limit caps the number of results, 1-50 (server cap). 0 = server default.
Limit int
// Mode selects the retrieval legs. Empty = server default (hybrid).
Mode CrawlerSearchMode
// Filters narrows the searched rows before each crawl's top-K, so a
// filter never costs recall. Keys: url_prefix, host, source_format,
// content_type, http_status, crawler_uuid. Unknown keys are rejected
// server-side rather than ignored.
Filters map[string]interface{}
// Cursor continues a previous response's ranking. Empty starts page 1.
Cursor string
}
CrawlSearchOptions configures a crawl search request. The zero value is valid: the server applies its own defaults for every unset field.
type CrawlURLsOptions ¶
type CrawlURLsOptions struct {
// Status filters by URL status. Empty = server default ("visited").
// Valid values: "visited", "pending", "failed", "skipped".
Status string
// Page is the 1-based page number. Zero = 1.
Page int
// PerPage is the page size. Zero = 100.
PerPage int
}
CrawlURLsOptions configures a GET /crawl/{uuid}/urls request.
type CrawlerArtifact ¶
type CrawlerArtifact struct {
Type CrawlerArtifactType
Data []byte
}
CrawlerArtifact holds the raw bytes of a downloaded WARC or HAR artifact.
The SDK does NOT bundle WARC/HAR parsers — use a dedicated Go library (e.g. nlnwa/gowarc) if you need to walk the records. The Save() method is provided for the common case of writing the artifact to disk.
func (*CrawlerArtifact) Len ¶
func (a *CrawlerArtifact) Len() int
Len returns the size of the artifact data in bytes.
func (*CrawlerArtifact) Save ¶
func (a *CrawlerArtifact) Save(path string) error
Save writes the artifact bytes to a file at the given path.
type CrawlerArtifactType ¶
type CrawlerArtifactType string
CrawlerArtifactType identifies the wire format of a crawler artifact.
const ( ArtifactTypeWARC CrawlerArtifactType = "warc" ArtifactTypeHAR CrawlerArtifactType = "har" )
Artifact type values accepted by GET /crawl/{uuid}/artifact?type=...
type CrawlerConfig ¶
type CrawlerConfig struct {
// URL source — exactly one of URL, URLList, RemoteURLList. URL enables
// discovery (sitemaps, robots.txt, link-following); URLList and
// RemoteURLList crawl exactly the URLs they reference, no discovery.
URL string
URLList []string
RemoteURLList string
// Crawl limits. Zero means "unset" — the server applies its own default.
PageLimit int
MaxDepth int
MaxDuration int // seconds, 15-10800
MaxAPICredit int // 0 means no limit per the docs
// Path filtering (mutually exclusive — validated at serialization time).
ExcludePaths []string `exclusive:"path_filter"`
IncludeOnlyPaths []string `exclusive:"path_filter"`
// Domain & subdomain restrictions.
IgnoreBasePathRestriction bool
FollowExternalLinks bool
AllowedExternalDomains []string
// Tri-state. nil = unset (server default True); non-nil = explicit override.
FollowInternalSubdomains *bool
AllowedInternalSubdomains []string
// Request configuration.
Headers map[string]string
Delay int // ms, 0-15000
UserAgent string
MaxConcurrency int
RenderingDelay int // ms, 0-25000
// Crawl strategy.
UseSitemaps bool
IgnoreNoFollow bool
// Tri-state. nil = unset (server default True); non-nil = explicit override.
RespectRobotsTxt *bool
// Cache.
Cache bool
CacheTTL int // seconds, 0-604800
CacheClear bool
// Content extraction.
ContentFormats []CrawlerContentFormat `validate:"enum"`
ExtractionRules map[string]interface{}
// Search index built while the crawl runs. Query it with CrawlSearch /
// CrawlPrompt once the index reaches READY.
Search bool
// Refresh keeps this crawl fresh: its own URLs are re-scraped in place on
// a period, under the same crawler UUID and the same artifacts. Only pages
// whose content changed are re-indexed and pages that disappeared are
// dropped.
Refresh bool
// RefreshInterval is the period in seconds, CrawlerRefreshMinInterval to
// CrawlerRefreshMaxInterval. Zero leaves the server default period.
RefreshInterval int
// Unblocker turns the Unblocker (anti-bot bypass, formerly "ASP") on.
//
// nil means unset; set it with BoolPtr(true) / BoolPtr(false).
// Serialized into the POST /crawl body under the "asp" key — the wire key
// is unchanged.
// See resolveUnblocker for the ASP/Unblocker precedence rule.
//
// The two names are two INDEPENDENT fields, not an aliased pair: writing
// one never updates the other, so reading Unblocker after setting ASP
// returns nil, and ASP: true wins no matter which was written last. To turn
// the feature off, clear ASP — setting Unblocker to BoolPtr(false) does not
// override an ASP: true. Use UnblockerEnabled to read what will actually go
// on the wire. The other Scrapfly SDKs expose one storage slot behind two
// names, so this and the ASP: false + Unblocker: BoolPtr(true) row are the
// two places Go answers differently; both follow from ASP being a plain
// bool, which cannot be retyped without breaking every existing caller.
Unblocker *bool
// ASP enables the Unblocker (formerly Anti-Scraping Protection).
//
// Deprecated: use Unblocker. ASP keeps working forever; it is only the
// documented name that changed. When ASP is true it wins over Unblocker,
// because a plain bool cannot distinguish "unset" from "explicitly false"
// and honouring it is the only way an old caller keeps its feature.
ASP bool
// ProxyPool is the proxy pool of every crawled page:
// "public_datacenter_pool" (the default), "public_residential_pool" or
// "public_tor_pool" (string(PublicDataCenterPool), ...).
ProxyPool string
Country string
// Webhook integration.
WebhookName string
WebhookEvents []CrawlerWebhookEvent `validate:"enum"`
}
CrawlerConfig configures a Scrapfly Crawler API job.
Exactly one URL source must be provided: URL (seed crawl with discovery), URLList (explicit in-memory list, no discovery), or RemoteURLList (URL of a hosted text file fetched at crawl start, no discovery). Other fields are optional and default to server-side values when zero-valued.
Tri-state fields (RespectRobotsTxt, FollowInternalSubdomains, Unblocker) use *bool so the SDK can distinguish "unset" from "explicit false". Setting a bool field directly (e.g. UseSitemaps=true) is sent as-is; only the tri-state fields need pointer semantics.
func (*CrawlerConfig) UnblockerEnabled ¶ added in v1.6.0
func (c *CrawlerConfig) UnblockerEnabled() bool
UnblockerEnabled reports whether the anti-bot bypass will be requested for this crawl. See ScrapeConfig.UnblockerEnabled.
type CrawlerContentFormat ¶
type CrawlerContentFormat string
CrawlerContentFormat represents the content format to extract from crawled pages.
Corresponds to the `content_formats` array on POST /crawl. The server-side contract permits any subset of these formats per crawler config.
const ( CrawlerFormatHTML CrawlerContentFormat = "html" CrawlerFormatCleanHTML CrawlerContentFormat = "clean_html" CrawlerFormatMarkdown CrawlerContentFormat = "markdown" CrawlerFormatText CrawlerContentFormat = "text" CrawlerFormatJSON CrawlerContentFormat = "json" CrawlerFormatExtractedData CrawlerContentFormat = "extracted_data" CrawlerFormatPageMetadata CrawlerContentFormat = "page_metadata" )
Content formats supported by the Crawler API.
func (CrawlerContentFormat) IsValid ¶
func (f CrawlerContentFormat) IsValid() bool
IsValid returns true when the format is one of the documented values. Used by the SDK's reflective enum validator.
func (CrawlerContentFormat) String ¶
func (f CrawlerContentFormat) String() string
String returns the wire-format value.
type CrawlerContents ¶
type CrawlerContents struct {
Contents map[string]map[string]string `json:"contents"`
Links CrawlerContentsLinks `json:"links"`
}
CrawlerContents wraps the JSON response of GET /crawl/{uuid}/contents (bulk mode, plain=false). The Contents map is URL → format → content.
For the single-URL `plain=true` mode, the client returns a raw string directly instead of this struct.
type CrawlerContentsLinks ¶
type CrawlerContentsLinks struct {
CrawledURLs string `json:"crawled_urls,omitempty"`
Next string `json:"next,omitempty"`
Prev string `json:"prev,omitempty"`
}
CrawlerContentsLinks is the pagination links block returned with bulk contents.
type CrawlerExtractResponse ¶ added in v1.7.0
type CrawlerExtractResponse struct {
Prompt string `json:"prompt"`
Data json.RawMessage `json:"data"`
// Sources are the retrieved chunks Data was built from.
Sources []CrawlerPromptSource `json:"sources"`
SourcesDropped int `json:"sources_dropped"`
Truncated bool `json:"truncated"`
Search CrawlerPromptSearch `json:"search"`
}
CrawlerExtractResponse is the answer of `POST /crawl/extract`. Data is the object the request's JSON Schema shaped, left encoded: Decode it into your own type. The schema constrains the model as it generates; it is not validated again afterwards, so validate anything you act on.
func (*CrawlerExtractResponse) Decode ¶ added in v1.7.0
func (r *CrawlerExtractResponse) Decode(v interface{}) error
Decode unmarshals Data into v.
type CrawlerLifecycleWebhook ¶
type CrawlerLifecycleWebhook struct {
Event CrawlerWebhookEvent `json:"event"`
Payload struct {
CrawlerWebhookCommon
SeedURL string `json:"seed_url"`
Links struct {
Status string `json:"status"`
} `json:"links"`
} `json:"payload"`
}
CrawlerLifecycleWebhook covers the four "lifecycle" events that share an identical payload shape: crawler_started, crawler_stopped, crawler_cancelled, crawler_finished. Verified against the example JSONs in the docs.
type CrawlerPromptAnswer ¶ added in v1.7.0
type CrawlerPromptAnswer struct {
Prompt string `json:"prompt"`
Answer string `json:"answer"`
Sources []CrawlerPromptSource `json:"sources"`
// SourcesUsed, SourcesDropped, Truncated and APICredit mean what they mean
// on CrawlerPromptDone.
SourcesUsed []int `json:"sources_used"`
SourcesDropped int `json:"sources_dropped"`
Truncated bool `json:"truncated"`
Search CrawlerPromptSearch `json:"search"`
APICredit *int `json:"api_credit"`
}
CrawlerPromptAnswer is the answer of `POST /crawl/prompt` with `generation.stream: false`: the facts of the stream, in one object.
type CrawlerPromptDone ¶ added in v1.6.0
type CrawlerPromptDone struct {
SourcesUsed []int `json:"sources_used"`
// SourcesDropped counts retrieved chunks that did not fit the context
// window. They were ranked in but never shown to the model, so an answer
// with SourcesDropped > 0 saw less than retrieval found.
SourcesDropped int `json:"sources_dropped"`
// Truncated is true when the model hit its output cap. The answer is
// returned anyway; it is the caller's call whether to use it.
Truncated bool `json:"truncated"`
// APICredit is what the engine actually charged, which is not always the
// list price: a run that produced no answer bills zero. Nil means an engine
// too old to report it, so fall back to the flat price rather than to zero.
APICredit *int `json:"api_credit,omitempty"`
}
CrawlerPromptDone is the terminal frame's payload. Token counts and the model id are deliberately absent: the API does not contract them, so the SDK drops them if an older engine sends them. The charge is the flat APICredit below.
type CrawlerPromptEvent ¶ added in v1.6.0
type CrawlerPromptEvent struct {
Type CrawlerPromptEventType
// Token holds the text delta for a token frame.
Token string
// Source is populated for a source frame.
Source CrawlerPromptSource
// Done is populated for the terminal frame.
Done CrawlerPromptDone
// Raw is the frame's undecoded data payload.
Raw []byte
}
CrawlerPromptEvent is one decoded frame of the prompt stream. Exactly one of the typed fields is populated, selected by Type.
type CrawlerPromptEventType ¶ added in v1.6.0
type CrawlerPromptEventType string
CrawlerPromptEventType names the SSE frames of POST /crawl/prompt.
const ( CrawlerPromptEventSource CrawlerPromptEventType = "source" CrawlerPromptEventToken CrawlerPromptEventType = "token" CrawlerPromptEventError CrawlerPromptEventType = "error" CrawlerPromptEventDone CrawlerPromptEventType = "done" )
Prompt stream frames, in emission order: sources first, then tokens, then exactly one done (or one error).
type CrawlerPromptSearch ¶ added in v1.7.0
type CrawlerPromptSearch struct {
Completeness string `json:"completeness"`
CrawlsRequested int `json:"crawls_requested"`
CrawlsSearched int `json:"crawls_searched"`
CrawlsPrunedExact int `json:"crawls_pruned_exact"`
Skipped []CrawlerSearchSkipped `json:"skipped"`
}
CrawlerPromptSearch says how much of the corpus a prompt answer or an extraction covers. A skipped crawl is never fatal.
type CrawlerPromptSource ¶ added in v1.6.0
type CrawlerPromptSource struct {
ID int `json:"id"`
CrawlerUUID string `json:"crawler_uuid"`
URL string `json:"url"`
Title string `json:"title"`
Score float64 `json:"score"`
}
CrawlerPromptSource identifies one retrieved chunk the answer may cite.
type CrawlerRefreshEntry ¶ added in v1.6.0
type CrawlerRefreshEntry struct {
At string `json:"at"`
Generation int `json:"generation"`
// Added are URLs this run discovered that the crawl did not hold; Updated
// are known URLs whose content fingerprint changed; Removed are known URLs
// that no longer exist and were dropped.
Added int `json:"added"`
Updated int `json:"updated"`
Removed int `json:"removed"`
// Unchanged pages were re-scraped with an identical fingerprint. They cost
// no embedding and no index write.
Unchanged int `json:"unchanged"`
// Failed URLs keep the content they already had.
Failed int `json:"failed"`
DurationMs int `json:"duration_ms"`
SearchStatus string `json:"search_status,omitempty"`
Error string `json:"error,omitempty"`
SampleUpdated []string `json:"sample_updated,omitempty"`
SampleRemoved []string `json:"sample_removed,omitempty"`
}
CrawlerRefreshEntry is one row of a crawl's refresh timeline.
SampleUpdated/SampleRemoved carry at most ten URLs each. The full lists are never inlined: a 5,000-page crawl would otherwise put 5,000 strings into every status poll.
func (*CrawlerRefreshEntry) Changed ¶ added in v1.6.0
func (e *CrawlerRefreshEntry) Changed() int
Changed reports the pages this run actually touched. Zero means the site stood still and the run cost no re-indexing.
type CrawlerRefreshState ¶ added in v1.6.0
type CrawlerRefreshState struct {
Enabled bool `json:"enabled"`
IntervalSeconds int `json:"interval_seconds"`
Status string `json:"status"`
// Generation counts completed refresh runs.
Generation int `json:"generation"`
LastRunAt string `json:"last_run_at,omitempty"`
// NextRunAt is empty while refresh is disabled.
NextRunAt string `json:"next_run_at,omitempty"`
// StartedAt is set only while a run is in flight, so it is the wall-clock
// answer to "how long has this been running", which LastRunAt cannot give.
StartedAt string `json:"started_at,omitempty"`
Error string `json:"error,omitempty"`
// ConsecutiveFailures resets on the first run that succeeds. It is the
// signal that separates one flaky run from a schedule that has stopped
// working, which Status alone does not say.
ConsecutiveFailures int `json:"consecutive_failures"`
// History is newest-last and capped at the 50 most recent runs.
History []CrawlerRefreshEntry `json:"history,omitempty"`
}
CrawlerRefreshState is a crawl's refresh block. It appears on GET /crawl/{uuid}/status and is the answer of the three refresh calls.
One type serves both paths, and the two paths do not carry the same keys: /status relays the engine's block verbatim, while the refresh calls render the API's own typed state, which declares neither StartedAt nor ConsecutiveFailures. Both therefore stay zero-valued on a refresh call and must not be read as "the crawl has never run".
func (*CrawlerRefreshState) IsRunning ¶ added in v1.6.0
func (r *CrawlerRefreshState) IsRunning() bool
IsRunning reports whether a refresh run is in flight right now.
func (*CrawlerRefreshState) LastRun ¶ added in v1.6.0
func (r *CrawlerRefreshState) LastRun() *CrawlerRefreshEntry
LastRun returns the most recent timeline row, nil before the first run.
type CrawlerSearchCrawl ¶ added in v1.6.0
type CrawlerSearchCrawl struct {
CrawlerUUID string `json:"crawler_uuid"`
Documents int `json:"documents"`
Vectors int `json:"vectors"`
Index string `json:"index"`
}
CrawlerSearchCrawl is a crawl that was opened and searched.
type CrawlerSearchMode ¶ added in v1.6.0
type CrawlerSearchMode string
CrawlerSearchMode selects which retrieval legs run.
const ( CrawlerSearchModeVector CrawlerSearchMode = "vector" CrawlerSearchModeFTS CrawlerSearchMode = "fts" CrawlerSearchModeHybrid CrawlerSearchMode = "hybrid" )
Search modes. Hybrid runs both legs and merges them with reciprocal rank fusion; it is the server default when the field is omitted.
func (CrawlerSearchMode) IsValid ¶ added in v1.6.0
func (m CrawlerSearchMode) IsValid() bool
IsValid returns true when the mode is one of the documented values.
func (CrawlerSearchMode) String ¶ added in v1.6.0
func (m CrawlerSearchMode) String() string
String returns the wire-format value.
type CrawlerSearchResponse ¶ added in v1.6.0
type CrawlerSearchResponse struct {
Query string `json:"query"`
Mode CrawlerSearchMode `json:"mode"`
Limit int `json:"limit"`
Completeness string `json:"completeness"`
Crawls []CrawlerSearchCrawl `json:"crawls"`
Skipped []CrawlerSearchSkipped `json:"skipped"`
Results []CrawlerSearchResult `json:"results"`
Stats CrawlerSearchStats `json:"stats"`
CrawlsRequested int `json:"crawls_requested"`
CrawlsSearched int `json:"crawls_searched"`
CrawlsPrunedExact int `json:"crawls_pruned_exact"`
// CrawlsSkippedDeadline and CrawlsFailed name the crawls, they do not count
// them: a caller told "3 failed" has nothing to retry. Both are lists on
// the wire even when empty, so an int here is a hard unmarshal error that
// turns every real search response into a parse failure.
CrawlsSkippedDeadline []string `json:"crawls_skipped_deadline"`
CrawlsFailed []CrawlerSearchSkipped `json:"crawls_failed"`
// Theta is the fusion cutoff and MaxUBUnsearched the best score an unopened
// crawl could still hold. The bound only exists once a crawl has been
// opened, and nil is not the claim 0 makes.
Theta *float64 `json:"theta"`
MaxUBUnsearched *float64 `json:"max_ub_unsearched"`
// Cursor pages the next slice. Paging is cursor-based: an offset over a
// partial fan-out would re-run the legs and shift ranks. Empty on the
// last page.
Cursor string `json:"cursor"`
}
CrawlerSearchResponse wraps the JSON response of POST /crawl/search.
The envelope states its own completeness. Completeness "exact" with most crawls unopened is the normal outcome: the fan-out proves via an admissible bound that the unopened crawls held nothing better. "partial" means the deadline cut the fan-out short.
func (*CrawlerSearchResponse) IsExact ¶ added in v1.6.0
func (r *CrawlerSearchResponse) IsExact() bool
IsExact reports whether the ranking is provably complete for the requested crawls.
type CrawlerSearchResult ¶ added in v1.6.0
type CrawlerSearchResult struct {
Rank int `json:"rank"`
Score float64 `json:"score"`
Scores CrawlerSearchScores `json:"scores"`
CrawlerUUID string `json:"crawler_uuid"`
URL string `json:"url"`
Title string `json:"title"`
SourceFormat string `json:"source_format"`
ContentType string `json:"content_type"`
ChunkID int `json:"chunk_id"`
Text string `json:"text"`
WARCOffset *int64 `json:"warc_offset"`
WARCEnd *int64 `json:"warc_end"`
ContentsURL string `json:"contents_url"`
}
CrawlerSearchResult is one matched chunk.
A result is a chunk, not a page: ChunkID orders chunks within one crawled document and Text is only the matched slice. Expand a hit back to the whole document through ContentsURL, or through WARCOffset/WARCEnd against the crawl's WARC artifact.
WARCOffset and WARCEnd are pointers because the index holds no byte range for a chunk the crawl never wrote to WARC, and the engine sends null there. Zero is a legal offset, so only nil can say the range is absent instead of pointing a range read at the head of the artifact.
type CrawlerSearchScores ¶ added in v1.6.0
type CrawlerSearchScores struct {
Vector *float64 `json:"vector"`
FTS *float64 `json:"fts"`
RRF float64 `json:"rrf"`
}
CrawlerSearchScores holds the per-leg scores behind a result. Which fields are populated depends on the mode.
Vector and FTS are pointers because a candidate found by only one leg has no score from the other and the engine sends null there. Decoded into a bare float64 that null becomes 0.0, which reads as "we scored it and it was orthogonal" rather than "that leg never saw it". RRF is always present.
type CrawlerSearchSkipped ¶ added in v1.6.0
type CrawlerSearchSkipped struct {
CrawlerUUID string `json:"crawler_uuid"`
Reason string `json:"reason"`
Status string `json:"status"`
}
CrawlerSearchSkipped is a requested crawl that contributed nothing, and why.
A skip is never fatal: the search still answers from the remaining crawls.
type CrawlerSearchState ¶ added in v1.6.0
type CrawlerSearchState struct {
Status string `json:"status"`
Manifest string `json:"manifest,omitempty"`
// Documents counts crawled pages represented in the index; Vectors counts
// the embedded chunks they were split into.
Documents int `json:"documents"`
Vectors int `json:"vectors"`
Dropped int `json:"dropped"`
// Fragments counts the index's on-disk data files. QueueDepth counts rows
// the writer accepted but has not flushed into one yet, so a nonzero
// QueueDepth on a terminal crawl means the index is still catching up.
Fragments int `json:"fragments"`
QueueDepth int `json:"queue_depth"`
Error string `json:"error,omitempty"`
BuiltAt string `json:"built_at,omitempty"`
// Index is the vector index type (e.g. IVF_PQ), empty when the row count
// stayed below the index threshold.
Index string `json:"index,omitempty"`
// Generation is bumped when a paused crawl resumes and rebuilds. Results
// from different generations are not comparable.
Generation int `json:"generation,omitempty"`
}
CrawlerSearchState describes a crawl's search index. It appears on GET /crawl/{uuid}/status and on the two search webhooks.
func (*CrawlerSearchState) IsSearchable ¶ added in v1.6.0
func (s *CrawlerSearchState) IsSearchable() bool
IsSearchable reports whether the index can answer a query right now.
type CrawlerSearchStats ¶ added in v1.6.0
type CrawlerSearchStats struct {
DurationMS int `json:"duration_ms"`
CrawlsSearched int `json:"crawls_searched"`
Candidates int `json:"candidates"`
GCSGets int `json:"gcs_gets"`
}
CrawlerSearchStats holds the fan-out's timing and IO counters.
type CrawlerStartResponse ¶
type CrawlerStartResponse struct {
CrawlerUUID string `json:"crawler_uuid"`
Status string `json:"status"`
}
CrawlerStartResponse is the response from POST /crawl.
type CrawlerState ¶
type CrawlerState struct {
URLsVisited int `json:"urls_visited"`
URLsExtracted int `json:"urls_extracted"`
URLsFailed int `json:"urls_failed"`
URLsSkipped int `json:"urls_skipped"`
URLsToCrawl int `json:"urls_to_crawl"`
APICreditUsed int `json:"api_credit_used"`
Duration int `json:"duration"`
// StartTime is the Unix timestamp when the first worker picked up the job.
// nil while the crawler is still PENDING.
StartTime *int64 `json:"start_time"`
// StopTime is the Unix timestamp when the crawler reached a terminal state.
// nil until the crawler is finished or cancelled.
StopTime *int64 `json:"stop_time"`
// StopReason is one of the documented stop-reason strings. nil while still running.
StopReason *string `json:"stop_reason"`
}
CrawlerState holds the per-job metrics returned inside CrawlerStatus.
Note on nullable fields: while the crawler is in PENDING (before any worker has picked up the job), StartTime, StopTime, and StopReason are all null on the wire and zero here (with HasStarted()/HasStopped() for disambiguation). They become populated once the crawl progresses.
func (*CrawlerState) HasStarted ¶
func (s *CrawlerState) HasStarted() bool
HasStarted reports whether the crawler has been picked up by a worker (i.e. StartTime is set).
func (*CrawlerState) HasStopped ¶
func (s *CrawlerState) HasStopped() bool
HasStopped reports whether the crawler reached a terminal state (i.e. StopTime is set).
type CrawlerStatus ¶
type CrawlerStatus struct {
CrawlerUUID string `json:"crawler_uuid"`
Status string `json:"status"`
IsFinished bool `json:"is_finished"`
// IsSuccess is nil while the crawler is still running, then bool once terminal.
// The server occasionally sends `false` during PENDING, so callers should use
// IsComplete() / IsFailed() rather than checking the field directly.
IsSuccess *bool `json:"is_success"`
State CrawlerState `json:"state"`
// Search is nil unless the crawl was started with Search=true. Polling it
// is the webhook-free way to learn when the index became queryable.
Search *CrawlerSearchState `json:"search"`
// Refresh is nil unless the crawl re-scrapes itself on a period.
Refresh *CrawlerRefreshState `json:"refresh"`
}
CrawlerStatus wraps the JSON response of GET /crawl/{uuid}/status.
Strict parsing: required fields (CrawlerUUID, Status, IsFinished, State and its documented counters) are validated after JSON unmarshal. A missing or zero required field throws an error so API contract drift surfaces loud rather than silently producing a zero-valued Status object.
func (*CrawlerStatus) IsCancelled ¶
func (s *CrawlerStatus) IsCancelled() bool
IsCancelled reports whether the crawler was cancelled by the user.
func (*CrawlerStatus) IsComplete ¶
func (s *CrawlerStatus) IsComplete() bool
IsComplete reports whether the crawler finished successfully.
func (*CrawlerStatus) IsFailed ¶
func (s *CrawlerStatus) IsFailed() bool
IsFailed reports whether the crawler reached DONE but failed.
func (*CrawlerStatus) IsRunning ¶
func (s *CrawlerStatus) IsRunning() bool
IsRunning reports whether the crawler is still PENDING or RUNNING.
func (*CrawlerStatus) ProgressPct ¶
func (s *CrawlerStatus) ProgressPct() float64
ProgressPct returns a rough progress estimate based on visited vs extracted URLs (0-100). Returns 0 when nothing has been extracted yet.
type CrawlerURLDiscoveredWebhook ¶
type CrawlerURLDiscoveredWebhook struct {
Event CrawlerWebhookEvent `json:"event"`
Payload struct {
CrawlerWebhookCommon
Origin string `json:"origin"`
DiscoveredURLs []string `json:"discovered_urls"`
} `json:"payload"`
}
CrawlerURLDiscoveredWebhook is the payload for the crawler_url_discovered event.
type CrawlerURLEntry ¶
type CrawlerURLEntry struct {
URL string
Status string // Echoed from the request filter (visited/pending/failed/skipped)
Reason string // Only set for failed/skipped URLs; empty otherwise
}
CrawlerURLEntry is a single URL record from GET /crawl/{uuid}/urls.
The endpoint streams one record per line as `text/plain`. For `visited`/ `pending` URLs each line is just the URL; for `failed`/`skipped` URLs the line is `url,reason`. Streaming text is intentional — the endpoint is expected to scale to millions of records per job where JSON would be too expensive both on the server and the client.
type CrawlerURLFailedWebhook ¶
type CrawlerURLFailedWebhook struct {
Event CrawlerWebhookEvent `json:"event"`
Payload struct {
CrawlerWebhookCommon
URL string `json:"url"`
Error string `json:"error"`
ScrapeConfig map[string]interface{} `json:"scrape_config"`
Links struct {
Log *string `json:"log"`
} `json:"links"`
} `json:"payload"`
}
CrawlerURLFailedWebhook is the payload for the crawler_url_failed event.
type CrawlerURLSkippedWebhook ¶
type CrawlerURLSkippedWebhook struct {
Event CrawlerWebhookEvent `json:"event"`
Payload struct {
CrawlerWebhookCommon
// URLs maps skipped URLs to their skip reason.
URLs map[string]string `json:"urls"`
} `json:"payload"`
}
CrawlerURLSkippedWebhook is the payload for the crawler_url_skipped event.
type CrawlerURLVisitedWebhook ¶
type CrawlerURLVisitedWebhook struct {
Event CrawlerWebhookEvent `json:"event"`
Payload struct {
CrawlerWebhookCommon
URL string `json:"url"`
Scrape struct {
StatusCode int `json:"status_code"`
Country string `json:"country,omitempty"`
LogUUID string `json:"log_uuid,omitempty"`
LogURL string `json:"log_url,omitempty"`
Content map[string]string `json:"content"`
} `json:"scrape"`
} `json:"payload"`
}
CrawlerURLVisitedWebhook is the payload for the crawler_url_visited event.
type CrawlerURLs ¶
type CrawlerURLs struct {
URLs []CrawlerURLEntry
Page int
PerPage int
}
CrawlerURLs wraps the streaming-text response of GET /crawl/{uuid}/urls.
Page and PerPage are echoes of the caller's request parameters — the wire protocol carries no global total count. Use len(URLs) for the page size and request further pages by incrementing Page until an empty response.
type CrawlerUpdatedWebhook ¶ added in v1.6.0
type CrawlerUpdatedWebhook struct {
Event CrawlerWebhookEvent `json:"event"`
Payload struct {
CrawlerWebhookCommon
SeedURL string `json:"seed_url"`
// Refresh is the run as the refresh timeline records it, minus the
// sample lists: this event carries the URLs in Documents instead, at a
// higher cap.
Refresh CrawlerRefreshEntry `json:"refresh"`
Documents struct {
// Updated holds the re-indexed URLs, added and changed alike.
// Which of the two a URL was only survives in the counts.
Updated []string `json:"updated"`
Removed []string `json:"removed"`
// Truncated reports that a list was cut at Scrapfly's 100-URL cap.
// The counts on Refresh still describe the whole run.
Truncated bool `json:"truncated"`
} `json:"documents"`
Links struct {
Status string `json:"status"`
} `json:"links"`
} `json:"payload"`
}
CrawlerUpdatedWebhook is the payload for the crawler_updated event, emitted once per auto-refresh run that changed at least one page. A run over a site that stood still, and a run that failed outright, change nothing and are not delivered, so receiving this event is by itself proof of a diff.
type CrawlerWebhookCommon ¶
type CrawlerWebhookCommon struct {
CrawlerUUID string `json:"crawler_uuid"`
Project string `json:"project"`
Env string `json:"env"`
Action string `json:"action"`
State CrawlerState `json:"state"`
}
CrawlerWebhookCommon holds the fields shared by every crawler webhook event.
type CrawlerWebhookEvent ¶
type CrawlerWebhookEvent string
CrawlerWebhookEvent enumerates the webhook events the crawler can emit.
Event names match the wire format documented in the Crawler API webhook reference, and are verified against its example payloads.
const ( WebhookCrawlerStarted CrawlerWebhookEvent = "crawler_started" WebhookCrawlerURLVisited CrawlerWebhookEvent = "crawler_url_visited" WebhookCrawlerURLSkipped CrawlerWebhookEvent = "crawler_url_skipped" WebhookCrawlerURLDiscovered CrawlerWebhookEvent = "crawler_url_discovered" WebhookCrawlerURLFailed CrawlerWebhookEvent = "crawler_url_failed" WebhookCrawlerStopped CrawlerWebhookEvent = "crawler_stopped" WebhookCrawlerCancelled CrawlerWebhookEvent = "crawler_cancelled" WebhookCrawlerFinished CrawlerWebhookEvent = "crawler_finished" WebhookCrawlerSearchReady CrawlerWebhookEvent = "crawler_search_ready" WebhookCrawlerSearchFailed CrawlerWebhookEvent = "crawler_search_failed" WebhookCrawlerUpdated CrawlerWebhookEvent = "crawler_updated" )
Crawler webhook event names.
func DetectCrawlerWebhookEvent ¶
func DetectCrawlerWebhookEvent(body []byte) (CrawlerWebhookEvent, error)
DetectCrawlerWebhookEvent peeks into a webhook request body and returns the event name without parsing the rest of the payload. Callers can then unmarshal into the appropriate typed webhook struct.
Example:
event, err := scrapfly.DetectCrawlerWebhookEvent(body)
if err != nil { return err }
switch event {
case scrapfly.WebhookCrawlerFinished:
var wh scrapfly.CrawlerLifecycleWebhook
json.Unmarshal(body, &wh)
// ...
case scrapfly.WebhookCrawlerURLVisited:
var wh scrapfly.CrawlerURLVisitedWebhook
json.Unmarshal(body, &wh)
// ...
}
func (CrawlerWebhookEvent) IsValid ¶
func (e CrawlerWebhookEvent) IsValid() bool
IsValid returns true when the event is one of the documented values.
func (CrawlerWebhookEvent) String ¶
func (e CrawlerWebhookEvent) String() string
String returns the wire-format value.
type CreateScheduleRequest ¶ added in v0.3.4
type CreateScheduleRequest struct {
WebhookName string `json:"webhook_name"`
Recurrence *ScheduleRecurrence `json:"recurrence,omitempty"`
ScheduledDate string `json:"scheduled_date,omitempty"`
AllowConcurrency bool `json:"allow_concurrency"`
RetryOnFailure bool `json:"retry_on_failure"`
MaxRetries int `json:"max_retries,omitempty"`
Notes string `json:"notes,omitempty"`
}
type DebugContext ¶
type DebugContext struct {
ResponseURL string `json:"response_url"`
ScreenshotURL interface{} `json:"screenshot_url"`
}
DebugContext contains URLs for debugging the request.
type Enumerable ¶
type ExtractionConfig ¶
type ExtractionConfig struct {
// Body is the document content to extract data from (required).
Body []byte `required:"true"`
// ContentType specifies the document content type, e.g., "text/html" (required).
ContentType string `required:"true"`
// URL is the original URL of the document (optional, helps with context).
URL string
// Charset specifies the character encoding of the document.
Charset string
// ExtractionTemplate is the name of a saved extraction template.
ExtractionTemplate string `exclusive:"extraction"`
// ExtractionEphemeralTemplate is an inline extraction template definition.
ExtractionEphemeralTemplate map[string]interface{} `exclusive:"extraction"`
// ExtractionPrompt is an AI prompt describing what data to extract.
ExtractionPrompt string `exclusive:"extraction"`
// ExtractionModel specifies which AI model to use for extraction.
ExtractionModel ExtractionModel `exclusive:"extraction" validate:"enum"`
// IsDocumentCompressed indicates if the Body is compressed.
IsDocumentCompressed bool
// DocumentCompressionFormat specifies the compression format if IsDocumentCompressed is true.
DocumentCompressionFormat CompressionFormat
// Webhook is the name of a webhook to call after extraction completes.
Webhook string
// Timeout is the maximum time in seconds for extraction processing.
Timeout int
}
ExtractionConfig configures an AI-powered data extraction request to the Scrapfly API.
This struct contains all available options for extracting structured data from HTML or other document formats using AI models or predefined templates.
Example with template:
config := &scrapfly.ExtractionConfig{
Body: []byte("<html>...</html>"),
ContentType: "text/html",
ExtractionTemplate: "product",
}
Example with AI prompt:
config := &scrapfly.ExtractionConfig{
Body: []byte("<html>...</html>"),
ContentType: "text/html",
ExtractionPrompt: "Extract product name, price, and description",
}
type ExtractionModel ¶
type ExtractionModel string
ExtractionModel defines the type of extraction model to use for extraction. see https://scrapfly.io/docs/extraction-api/automatic-ai#models
const ( ExtractionModelArticle ExtractionModel = "article" ExtractionModelEvent ExtractionModel = "event" ExtractionModelFoodRecipe ExtractionModel = "food_recipe" ExtractionModelHotel ExtractionModel = "hotel" ExtractionModelHotelListing ExtractionModel = "hotel_listing" ExtractionModelJobListing ExtractionModel = "job_listing" ExtractionModelJobPosting ExtractionModel = "job_posting" ExtractionModelOrganization ExtractionModel = "organization" ExtractionModelProduct ExtractionModel = "product" ExtractionModelProductListing ExtractionModel = "product_listing" ExtractionModelRealEstateProperty ExtractionModel = "real_estate_property" ExtractionModelRealEstatePropertyListing ExtractionModel = "real_estate_property_listing" ExtractionModelReviewList ExtractionModel = "review_list" ExtractionModelSearchEngineResults ExtractionModel = "search_engine_results" ExtractionModelSocialMediaPost ExtractionModel = "social_media_post" ExtractionModelSoftware ExtractionModel = "software" ExtractionModelStock ExtractionModel = "stock" ExtractionModelVehicleAd ExtractionModel = "vehicle_ad" ExtractionModelVehicleAdListing ExtractionModel = "vehicle_ad_listing" ExtractionModelNone ExtractionModel = "" )
func (ExtractionModel) AnyEnum ¶
func (f ExtractionModel) AnyEnum() []any
func (ExtractionModel) Enum ¶
func (f ExtractionModel) Enum() []ExtractionModel
func (ExtractionModel) IsValid ¶
func (f ExtractionModel) IsValid() bool
func (ExtractionModel) String ¶
func (f ExtractionModel) String() string
type ExtractionResult ¶
type ExtractionResult struct {
// Data contains the extracted structured data.
Data interface{} `json:"data"`
// ContentType is the content type of the extracted data.
ContentType string `json:"content_type"`
// DataQuality indicates the quality/confidence of the extraction (if available).
DataQuality interface{} `json:"data_quality,omitempty"`
}
ExtractionResult represents the result of a data extraction request.
type Format ¶
type Format string
Format defines the format for the scraped content response.
const ( // FormatJSON returns content structured as JSON. FormatJSON Format = "json" // FormatText returns plain text content with HTML tags stripped. FormatText Format = "text" // FormatMarkdown converts HTML to Markdown format. FormatMarkdown Format = "markdown" // FormatCleanHTML returns cleaned and normalized HTML. FormatCleanHTML Format = "clean_html" // FormatRaw returns the raw HTML content without any processing. FormatRaw Format = "raw" )
Available content formats for scrape responses.
type FormatOption ¶
type FormatOption string
FormatOption defines additional options for content formatting.
const ( // NoLinks removes all links from the formatted content. NoLinks FormatOption = "no_links" // NoImages removes all images from the formatted content. NoImages FormatOption = "no_images" // OnlyContent extracts only the main content, removing headers, footers, and navigation. OnlyContent FormatOption = "only_content" )
Available format options that can be combined with Format settings.
func (FormatOption) AnyEnum ¶
func (f FormatOption) AnyEnum() []any
func (FormatOption) Enum ¶
func (f FormatOption) Enum() []FormatOption
func (FormatOption) IsValid ¶
func (f FormatOption) IsValid() bool
func (FormatOption) String ¶
func (f FormatOption) String() string
type HarArchive ¶
type HarArchive struct {
// contains filtered or unexported fields
}
HarArchive wraps a parsed HAR file with high-level accessors.
Supports both the standard HAR format (single JSON object with `log.entries`) and Scrapfly's streaming HAR format (concatenated JSON objects: a leading `log` object followed by individual entry objects).
Example:
artifact, _ := client.CrawlArtifact(uuid, scrapfly.ArtifactTypeHAR)
archive, err := scrapfly.ParseHAR(artifact.Data)
if err != nil { log.Fatal(err) }
for _, entry := range archive.Entries() {
fmt.Printf("%s %s [%d]\n", entry.Method(), entry.URL(), entry.StatusCode())
}
func ParseHAR ¶
func ParseHAR(data []byte) (*HarArchive, error)
ParseHAR decodes a HAR byte stream into a HarArchive. Auto-detects gzip- compressed input by checking the magic bytes.
func (*HarArchive) Creator ¶
func (a *HarArchive) Creator() map[string]interface{}
Creator returns the creator info block (`{name, version, comment}`).
func (*HarArchive) Entries ¶
func (a *HarArchive) Entries() []*HarEntry
Entries returns every entry in the archive as a list of HarEntry wrappers.
func (*HarArchive) FilterByContentType ¶
func (a *HarArchive) FilterByContentType(contentType string) []*HarEntry
FilterByContentType returns every entry whose Content-Type contains the given substring (case-sensitive). Useful for collecting all HTML responses, JavaScript files, images, etc.
func (*HarArchive) FilterByStatus ¶
func (a *HarArchive) FilterByStatus(statusCode int) []*HarEntry
FilterByStatus returns every entry whose response has the given HTTP status code.
func (*HarArchive) FindByURL ¶
func (a *HarArchive) FindByURL(url string) *HarEntry
FindByURL returns the first entry whose request URL exactly matches `url`, or nil if no entry matches.
func (*HarArchive) IterEntries ¶
func (a *HarArchive) IterEntries(fn func(*HarEntry) bool)
IterEntries calls fn for each entry; iteration stops when fn returns false.
func (*HarArchive) Len ¶
func (a *HarArchive) Len() int
Len returns the number of entries in the archive.
func (*HarArchive) Pages ¶
func (a *HarArchive) Pages() []map[string]interface{}
Pages returns the HAR pages list (each page is a free-form map).
func (*HarArchive) URLs ¶
func (a *HarArchive) URLs() []string
URLs returns every distinct URL in the archive in entry order.
func (*HarArchive) Version ¶
func (a *HarArchive) Version() string
Version returns the HAR file format version (e.g. "1.2").
type HarEntry ¶
type HarEntry struct {
// contains filtered or unexported fields
}
HarEntry wraps a single HAR entry (one HTTP request/response pair).
Mirrors the Python SDK's HarEntry class. The accessors live behind getter methods (rather than exporting raw maps) so the SDK can normalise the `headers: [{name, value}, ...]` array form into a Go-friendly map.
func NewHarEntry ¶
NewHarEntry constructs a HarEntry from a decoded HAR entry map. Mostly used internally by HarArchive.GetEntries; exported for tests and for callers that already have a parsed HAR map.
func (*HarEntry) Content ¶
Content returns the raw response body bytes.
HAR stores response bodies as text inside `content.text`. When the body is binary or non-UTF-8, the producer base64-encodes it and sets `content.encoding = "base64"`. We honour both forms.
func (*HarEntry) ContentSize ¶
ContentSize returns the response body size in bytes (`response.content.size`).
func (*HarEntry) ContentType ¶
ContentType returns the response Content-Type (from `response.content.mimeType`).
func (*HarEntry) RequestHeaders ¶
RequestHeaders returns the request headers as a flat map.
HAR stores headers as `[{name, value}, ...]` to preserve duplicates and order; we collapse duplicates by keeping the last occurrence. Use the raw data via NewHarEntry's input if you need the full ordered list.
func (*HarEntry) ResponseHeaders ¶
ResponseHeaders returns the response headers as a flat map.
func (*HarEntry) StartedDateTime ¶
StartedDateTime returns the ISO 8601 timestamp when the request started.
func (*HarEntry) StatusCode ¶
StatusCode returns the HTTP response status code, or 0 if missing.
func (*HarEntry) StatusText ¶
StatusText returns the HTTP response status text (e.g. "OK", "Not Found").
type HttpMethod ¶
type HttpMethod string
const ( HttpMethodGet HttpMethod = http.MethodGet HttpMethodPost HttpMethod = http.MethodPost HttpMethodPut HttpMethod = http.MethodPut HttpMethodPatch HttpMethod = http.MethodPatch HttpMethodOptions HttpMethod = http.MethodOptions HttpMethodHead HttpMethod = http.MethodHead )
func (HttpMethod) AnyEnum ¶
func (f HttpMethod) AnyEnum() []any
func (HttpMethod) Enum ¶
func (f HttpMethod) Enum() []HttpMethod
func (HttpMethod) IsValid ¶
func (f HttpMethod) IsValid() bool
func (HttpMethod) String ¶
func (f HttpMethod) String() string
type IFrame ¶
type IFrame struct {
URL string `json:"url"`
URI URIContext `json:"uri"`
Content string `json:"content"`
}
IFrame represents an iframe found in the page.
type ListSchedulesOptions ¶ added in v0.3.4
type LogLevel ¶
type LogLevel int
LogLevel defines the severity level for log messages.
const ( // LevelDebug logs all messages including detailed debug information. LevelDebug LogLevel = iota // LevelInfo logs informational messages and above. LevelInfo // LevelWarn logs warnings and errors. LevelWarn // LevelError logs only error messages. LevelError )
Available log levels, from most to least verbose.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger provides simple leveled logging for the Scrapfly SDK.
func NewLogger ¶
NewLogger creates a new Logger instance with the given name prefix.
Example:
logger := scrapfly.NewLogger("my-scraper")
logger.SetLevel(scrapfly.LevelDebug)
logger.Info("Starting scraper...")
func (*Logger) Debug ¶
func (l *Logger) Debug(v ...interface{})
Debug logs a debug-level message. These messages are only logged when the level is set to LevelDebug.
func (*Logger) Error ¶
func (l *Logger) Error(v ...interface{})
Error logs an error message. These messages are always logged regardless of the level setting.
func (*Logger) Info ¶
func (l *Logger) Info(v ...interface{})
Info logs an informational message. These messages are logged when the level is LevelInfo or lower.
type MonitoringAggregation ¶ added in v0.3.0
type MonitoringAggregation string
MonitoringAggregation selects which aggregation level(s) to return for /scrape/monitoring/metrics. Multiple values can be combined.
const ( MonitoringAggregationAccount MonitoringAggregation = "account" MonitoringAggregationProject MonitoringAggregation = "project" MonitoringAggregationTarget MonitoringAggregation = "target" )
type MonitoringDataFormat ¶ added in v0.3.0
type MonitoringDataFormat string
MonitoringDataFormat controls the response format of the Monitoring API. "structured" returns JSON aggregates (default); "prometheus" returns a Prometheus-compatible text exposition.
const ( MonitoringDataFormatStructured MonitoringDataFormat = "structured" MonitoringDataFormatPrometheus MonitoringDataFormat = "prometheus" )
type MonitoringMetricsOptions ¶ added in v0.3.0
type MonitoringMetricsOptions struct {
Format MonitoringDataFormat
Period MonitoringPeriod
Aggregation []MonitoringAggregation
// IncludeWebhook folds events with origin=WEBHOOK (callbacks
// executed by the webhook worker) into this product's totals.
// Defaults to false to match the dashboard's default view.
IncludeWebhook bool
}
MonitoringMetricsOptions configures a Get*MonitoringMetrics call. All fields are optional — an empty struct returns account aggregates for the last 24 hours in structured JSON.
type MonitoringPeriod ¶ added in v0.3.0
type MonitoringPeriod string
MonitoringPeriod is a pre-defined time window for monitoring queries. Mutually exclusive with explicit start/end.
const ( MonitoringPeriodLast5m MonitoringPeriod = "last5m" MonitoringPeriodLast1h MonitoringPeriod = "last1h" MonitoringPeriodLast24h MonitoringPeriod = "last24h" MonitoringPeriodLast7d MonitoringPeriod = "last7d" MonitoringPeriodSubscription MonitoringPeriod = "subscription" )
type MonitoringTargetMetricsOptions ¶ added in v0.3.0
type MonitoringTargetMetricsOptions struct {
Domain string
GroupSubdomain bool
Period MonitoringPeriod
Start time.Time
End time.Time
IncludeWebhook bool
}
MonitoringTargetMetricsOptions configures a Get*MonitoringTargetMetrics call. Domain is required. Start/End are mutually exclusive with Period; both must be set together.
type NetworkPolicy ¶ added in v1.9.0
type NetworkPolicy struct {
Allow []string `json:"allow,omitempty"`
Block []string `json:"block,omitempty"`
}
NetworkPolicy allows or blocks domains (including their subdomains) and IP addresses.
type OSContext ¶
type OSContext struct {
Distribution string `json:"distribution"`
Name string `json:"name"`
Type string `json:"type"`
Version string `json:"version"`
}
OSContext contains information about the operating system used for the request.
type PlaywrightCDPSession ¶ added in v1.8.0
type PlaywrightCDPSession interface {
Send(method string, params map[string]interface{}) (interface{}, error)
}
PlaywrightCDPSession is the method set of playwright-go's CDPSession.
type Project ¶
type Project struct {
AllowExtraUsage bool `json:"allow_extra_usage"`
AllowedNetworks []string `json:"allowed_networks"`
BudgetLimit *float32 `json:"budget_limit"`
BudgetSpent *float32 `json:"budget_spent"`
ConcurrencyLimit *int `json:"concurrency_limit"`
Name string `json:"name"`
QuotaReached bool `json:"quota_reached"`
ScrapeRequestCount int `json:"scrape_request_count"`
ScrapeRequestLimit *int `json:"scrape_request_limit"`
Tags []string `json:"tags"`
}
type ProxyContext ¶
type ProxyContext struct {
Country string `json:"country"`
Identity string `json:"identity"`
Network string `json:"network"`
// Pool is the proxy pool the request ran on.
Pool string `json:"pool"`
}
ProxyContext contains information about the proxy used for the request.
type ProxyPool ¶
type ProxyPool string
ProxyPool is the proxy_pool parameter of the Web Scraping API and the Crawler: PublicDataCenterPool (the default), PublicResidentialPool or PublicTorPool. The anti-bot bypass is a parameter of its own: Unblocker.
const ( // PublicDataCenterPool routes through datacenter proxies, the default pool. PublicDataCenterPool ProxyPool = "public_datacenter_pool" // PublicResidentialPool routes through residential proxies. PublicResidentialPool ProxyPool = "public_residential_pool" // PublicTorPool routes egress through the Tor network, the only pool that // reaches .onion hidden services; also used for OSINT. PublicTorPool ProxyPool = "public_tor_pool" )
Proxy pools.
const ( ProxyPoolBasic ProxyPool = "basic" ProxyPoolUnblocker ProxyPool = "unblocker" ProxyPoolUnblockerUltra ProxyPool = "unblocker_ultra" ProxyPoolAuto ProxyPool = "auto" )
Pool names the API does not accept yet: a request naming one fails with ERR::PROXY::POOL_NOT_FOUND.
type ResultData ¶
type ResultData struct {
BrowserData BrowserData `json:"browser_data"`
Content string `json:"content"`
ContentEncoding string `json:"content_encoding"`
ContentType string `json:"content_type"`
Cookies []Cookie `json:"cookies"`
Data interface{} `json:"data"`
DNS interface{} `json:"dns"`
Duration float64 `json:"duration"`
Error *APIErrorDetails `json:"error"`
Format string `json:"format"`
IFrames []IFrame `json:"iframes"`
LogURL string `json:"log_url"`
Reason string `json:"reason"`
RequestHeaders map[string]string `json:"request_headers"`
ResponseHeaders map[string]interface{} `json:"response_headers"` // Can be string or []string
Screenshots map[string]Screenshot `json:"screenshots"`
Size int `json:"size"`
SSL interface{} `json:"ssl"`
Status string `json:"status"`
StatusCode int `json:"status_code"`
Success bool `json:"success"`
URL string `json:"url"`
ExtractedData *ExtractionResult `json:"extracted_data"`
}
ResultData contains the scraped content and response information. This is the main data from the scrape request including HTML content, status codes, headers, cookies, and more.
type RodCaller ¶ added in v1.8.0
type RodCaller interface {
Call(ctx context.Context, sessionID, methodName string, params interface{}) ([]byte, error)
}
RodCaller is the method set of go-rod's *rod.Page and *rod.Browser.
type Schedule ¶ added in v0.3.4
type Schedule struct {
ID string `json:"id"`
Kind string `json:"kind"`
Status string `json:"status"`
NextScheduledDate *string `json:"next_scheduled_date,omitempty"`
ScheduledDate *string `json:"scheduled_date,omitempty"`
Recurrence *ScheduleRecurrence `json:"recurrence,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
Notes *string `json:"notes,omitempty"`
CreatedBy *string `json:"created_by,omitempty"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
CancelledAt *string `json:"cancelled_at,omitempty"`
AllowConcurrency bool `json:"allow_concurrency"`
RetryOnFailure bool `json:"retry_on_failure"`
MaxRetries int `json:"max_retries"`
WebhookUUID *string `json:"webhook_uuid,omitempty"`
UserUUID *string `json:"user_uuid,omitempty"`
ConsecutiveFailures int `json:"consecutive_failures,omitempty"`
}
type ScheduleEnd ¶ added in v0.3.4
type ScheduleRecurrence ¶ added in v0.3.4
type ScheduleRecurrence struct {
Cron string `json:"cron,omitempty"`
Interval int `json:"interval,omitempty"`
Unit string `json:"unit,omitempty"`
Days []string `json:"days,omitempty"`
Ends *ScheduleEnd `json:"ends,omitempty"`
}
type ScheduleUsage ¶
type ScrapeConfig ¶
type ScrapeConfig struct {
// URL is the target URL to scrape (required).
URL string `required:"true"`
// Method is the HTTP method to use (GET, POST, PUT, PATCH). Defaults to GET.
Method HttpMethod
// Body is the raw request body for POST/PUT/PATCH requests.
Body string
// Data is a map that will be encoded as request body based on Content-Type.
// Cannot be used together with Body.
Data map[string]interface{}
// Headers are custom HTTP headers to send with the request.
Headers map[string]string
// Cookies are cookies to include in the request.
Cookies map[string]string
// Country accepts a country code, a comma-separated list, exclusions
// ("-us,-ca"), or weighted entries ("us:1,ca:2").
Country string
// ProxyPool selects the proxy pool: PublicDataCenterPool (the default),
// PublicResidentialPool or PublicTorPool. Empty sends no proxy_pool.
ProxyPool ProxyPool
// RenderJS enables JavaScript rendering using a headless browser.
RenderJS bool
// Unblocker turns the Unblocker (anti-bot bypass, formerly "ASP") on.
//
// nil means unset; set it with BoolPtr(true) / BoolPtr(false).
// Serialized as the "asp" query parameter — the wire key is unchanged.
// See resolveUnblocker for the ASP/Unblocker precedence rule.
//
// The two names are two INDEPENDENT fields, not an aliased pair: writing
// one never updates the other, so reading Unblocker after setting ASP
// returns nil, and ASP: true wins no matter which was written last. To turn
// the feature off, clear ASP — setting Unblocker to BoolPtr(false) does not
// override an ASP: true. Use UnblockerEnabled to read what will actually go
// on the wire. The other Scrapfly SDKs expose one storage slot behind two
// names, so this and the ASP: false + Unblocker: BoolPtr(true) row are the
// two places Go answers differently; both follow from ASP being a plain
// bool, which cannot be retyped without breaking every existing caller.
Unblocker *bool
// ASP enables the Unblocker (formerly Anti-Scraping Protection).
//
// Deprecated: use Unblocker. ASP keeps working forever; it is only the
// documented name that changed. When ASP is true it wins over Unblocker,
// because a plain bool cannot distinguish "unset" from "explicitly false"
// and honouring it is the only way an old caller keeps its feature.
ASP bool
// Cache enables response caching.
Cache bool
// CacheTTL sets the cache time-to-live in seconds.
CacheTTL int
// CacheClear forces cache refresh for this request.
CacheClear bool
// Timeout sets the maximum time in milliseconds to wait for the request.
Timeout int
// Retry enables automatic retries on failure. The zero value sends
// retry=false and turns them off: set Retry: true to keep them.
Retry bool
// Session maintains a persistent browser session across requests.
Session string
// SessionStickyProxy keeps the same proxy for all requests in a session.
// nil means the server default (sticky on); set to &false to opt out.
SessionStickyProxy *bool
// Tags are custom tags for organizing and filtering requests.
Tags []string
// Webhook is the name of a webhook to call after the request completes.
Webhook string
// Debug enables debug mode for viewing request details in the dashboard.
Debug bool
// SSL enables SSL certificate verification details capture.
SSL bool
// DNS enables DNS resolution details capture.
DNS bool
// CorrelationID is a custom ID for tracking requests across systems.
CorrelationID string
// Format specifies the output format for the scraped content.
Format Format `validate:"enum"`
// FormatOptions are additional options for the content format.
FormatOptions []FormatOption `validate:"enum"`
// ExtractionTemplate is the name of a saved extraction template.
// it is exclusve with other extraction options
ExtractionTemplate string `exclusive:"extraction"`
// ExtractionEphemeralTemplate is an inline extraction template definition.
// it is exclusve with other extraction options
ExtractionEphemeralTemplate map[string]interface{} `exclusive:"extraction"`
// ExtractionPrompt is an AI prompt for extracting structured data.
// it is exclusve with other extraction options
ExtractionPrompt string `exclusive:"extraction"`
// ExtractionModel specifies which AI model to use for extraction.
// it is exclusve with other extraction options
ExtractionModel ExtractionModel `exclusive:"extraction" validate:"enum"`
// WaitForSelector waits for a CSS selector to appear before capturing (requires RenderJS).
WaitForSelector string
// RenderingWait is additional wait time in milliseconds after page load (requires RenderJS).
RenderingWait int
// AutoScroll automatically scrolls the page to load lazy content (requires RenderJS).
AutoScroll bool
// Screenshots is a map of screenshot names to CSS selectors (requires RenderJS).
Screenshots map[string]string
// ScreenshotFlags are options for screenshot capture.
ScreenshotFlags []ScreenshotFlag `validate:"enum"`
// JS is custom JavaScript code to execute in the browser (requires RenderJS).
JS string
// JSScenario is a sequence of browser actions to perform (requires RenderJS).
JSScenario []js_scenario.JSScenarioStep
// OS spoofs the operating system in the User-Agent: win11, mac, linux, chromeos, android, iphone, ipad.
OS string
// Lang sets the Accept-Language header values.
Lang []string
// BrowserBrand selects the Chromium-based browser for fingerprint generation.
// Valid values: "chrome", "edge", "brave", "opera". Empty = default chrome.
// Invalid values are silently dropped by the server.
BrowserBrand string
// CostBudget limits the maximum API credit cost for unblocker retries.
// The unblocker dynamically upgrades proxy/browser to bypass protection;
// this caps spending.
CostBudget int
// Geolocation spoofs the browser's geolocation. Format: "latitude,longitude".
Geolocation string
// RenderingStage controls when the browser considers the page loaded (requires RenderJS).
// Valid values: "complete" (default), "domcontentloaded".
RenderingStage string
// ProxifiedResponse returns the raw upstream response (target's status,
// headers, body) instead of the JSON envelope. When true, callers must
// use ScrapeProxified() instead of Scrape(), which returns *http.Response.
ProxifiedResponse bool
}
ScrapeConfig configures a web scraping request to the Scrapfly API.
This struct contains all available options for customizing scraping behavior, including proxy settings, JavaScript rendering, data extraction, and more.
Example:
config := &scrapfly.ScrapeConfig{
URL: "https://web-scraping.dev",
Country: "us",
Unblocker: scrapfly.BoolPtr(true),
Cache: true,
Format: scrapfly.FormatMarkdown,
}
func (*ScrapeConfig) UnblockerEnabled ¶ added in v1.6.0
func (c *ScrapeConfig) UnblockerEnabled() bool
UnblockerEnabled reports whether the anti-bot bypass will be requested — the single resolved value that reaches the wire as "asp".
It exists because ASP and Unblocker are two independent exported fields rather than one slot behind two names. Without it there is no way to read back what a config will actually do: `cfg.Unblocker` is nil after `cfg.ASP = true`, and `cfg.ASP` is false after `cfg.Unblocker = BoolPtr(true)`. The Python, TypeScript and Rust SDKs all expose the resolved value under both names; this is Go's equivalent read surface (Rust spells it `unblocker_enabled()`).
type ScrapeResult ¶
type ScrapeResult struct {
// Config contains the configuration used for this scrape request.
Config ConfigData `json:"config"`
// Context contains metadata about the request execution.
Context ContextData `json:"context"`
// Result contains the scraped content and response data.
Result ResultData `json:"result"`
// UUID is the unique identifier for this scrape request.
UUID string `json:"uuid"`
// contains filtered or unexported fields
}
ScrapeResult represents the complete response from a scrape request.
It contains the scraped content, metadata, configuration, and context information about the request. The result includes details about the upstream response, proxy used, cost, and more.
func (*ScrapeResult) SaveAttachments ¶
func (r *ScrapeResult) SaveAttachments(savePath ...string) ([]string, error)
SaveAttachments is a shortcut to save all attachments to disk
Parameters:
- savePath: Optional directory path where to save the files (defaults to current directory) (if savePath does not exists, it will be created in a best effort basis)
Returns the full paths to the saved files.
Example:
paths, err := r.SaveAttachments("./attachments")
if err != nil {
log.Fatal(err)
}
for _, path := range paths {
fmt.Printf("Attachment saved to: %s\n", path)
}
func (*ScrapeResult) SaveScreenshots ¶
func (r *ScrapeResult) SaveScreenshots(savePath ...string) ([]string, error)
SaveScreenshots is a shortcut to save all screenshots to disk
Parameters:
- savePath: Optional directory path where to save the files (defaults to current directory) (if savePath does not exists, it will be created in a best effort basis)
Returns the full paths to the saved files.
Example:
paths, err := r.SaveScreenshots("./screenshots")
if err != nil {
log.Fatal(err)
}
for _, path := range paths {
fmt.Printf("Screenshot saved to: %s\n", path)
}
func (*ScrapeResult) Selector ¶
func (r *ScrapeResult) Selector() (*goquery.Document, error)
Selector provides a goquery document for parsing HTML content.
The selector is lazy-loaded and cached using sync.Once, making it safe for concurrent use. It can only be used with HTML content.
Example:
result, err := client.Scrape(config)
if err != nil {
log.Fatal(err)
}
doc, err := result.Selector()
if err != nil {
log.Fatal(err)
}
title := doc.Find("title").First().Text()
fmt.Println(title)
type ScrapeUsage ¶
type Screenshot ¶
type Screenshot struct {
// CSSSelector is the CSS selector of the element to capture. If Format == fullpage, this will be nil
CSSSelector *string `json:"css_selector"`
// Extension is the file extension (jpg, png, webp, gif)
Extension string `json:"extension"` // Always jpg when request from scraping api.
// Format is the format of the screenshot (fullpage, element)
Format string `json:"format"`
// Size is the size of the screenshot in bytes
Size int `json:"size"`
// URL is the URL to retrieve the screenshot from
URL string `json:"url"`
// Name is the name of the screenshot retrieved from the API response
Name string `json:"-"`
// contains filtered or unexported fields
}
Screenshot represents a screenshot captured during rendering.
func (*Screenshot) Image ¶
func (s *Screenshot) Image() ([]byte, error)
Image returns the screenshot data as a byte slice.
func (*Screenshot) Save ¶
func (s *Screenshot) Save(savePath ...string) (string, error)
Save saves a scraped screenshot result to disk.
Parameters:
- savePath: Optional directory path where to save the file (defaults to current directory) (if savePath does not exists, it will be created in a best effort basis)
it is named as the name of the screenshot as set in config and retrieved from the API response Returns the full path to the saved file.
Example:
filePath, err := s.Save("./screenshots")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Screenshot saved to: %s\n", filePath)
type ScreenshotConfig ¶
type ScreenshotConfig struct {
// URL is the target URL to capture (required).
URL string
// Format specifies the image format (jpg, png, webp, gif).
Format ScreenshotFormat
// Capture defines what to capture: "fullpage" for entire page, or a CSS selector for specific element.
Capture string
// Resolution sets the viewport size (e.g., "1920x1080").
Resolution string
// Country accepts a country code, a comma-separated list, or exclusions
// ("-us,-ca").
Country string
// Timeout sets the maximum time in milliseconds to wait for the request.
Timeout int
// RenderingWait is additional wait time in milliseconds after page load.
RenderingWait int
// WaitForSelector waits for a CSS selector to appear before capturing.
WaitForSelector string
// Options are additional screenshot options (dark mode, block banners, etc.).
Options []ScreenshotOption
// AutoScroll automatically scrolls the page to load lazy content.
AutoScroll bool
// JS is custom JavaScript code to execute before capturing.
JS string
// Cache enables response caching.
Cache bool
// CacheTTL sets the cache time-to-live in seconds.
CacheTTL int
// CacheClear forces cache refresh for this request.
CacheClear bool
// Webhook is the name of a webhook to call after the request completes.
Webhook string
// VisionDeficiencyType specifies the type of vision deficiency to simulate.
// see https://scrapfly.io/docs/screenshot-api/accessibility#vision_deficiency
VisionDeficiencyType VisionDeficiencyType
// ProxyPool is sent as proxy_pool. The Screenshot API picks its pool itself
// and ignores this value. Empty sends no proxy_pool.
ProxyPool ProxyPool
}
ScreenshotConfig configures a screenshot capture request to the Scrapfly API.
This struct contains all available options for customizing screenshot behavior, including format, resolution, capture area, and rendering options.
Example:
config := &scrapfly.ScreenshotConfig{
URL: "https://web-scraping.dev",
Format: scrapfly.FormatPNG,
Capture: "fullpage",
Resolution: "1920x1080",
Options: []scrapfly.ScreenshotOption{scrapfly.OptionBlockBanners},
}
type ScreenshotFlag ¶
type ScreenshotFlag string
ScreenshotFlag defines options for screenshot behavior when using Screenshots parameter.
const ( // LoadImages enables image loading for screenshots (disabled by default for performance). LoadImages ScreenshotFlag = "load_images" // DarkMode enables dark mode rendering. DarkMode ScreenshotFlag = "dark_mode" // BlockBanners blocks cookie banners and similar overlays. BlockBanners ScreenshotFlag = "block_banners" // PrintMediaFormat uses print media CSS for rendering. PrintMediaFormat ScreenshotFlag = "print_media_format" // HighQuality captures screenshots at higher quality settings. HighQuality ScreenshotFlag = "high_quality" )
Available screenshot flags for customizing screenshot capture.
func (ScreenshotFlag) AnyEnum ¶
func (f ScreenshotFlag) AnyEnum() []any
func (ScreenshotFlag) Enum ¶
func (f ScreenshotFlag) Enum() []ScreenshotFlag
func (ScreenshotFlag) IsValid ¶
func (f ScreenshotFlag) IsValid() bool
func (ScreenshotFlag) String ¶
func (f ScreenshotFlag) String() string
type ScreenshotFormat ¶
type ScreenshotFormat string
ScreenshotFormat defines the image format for screenshots.
const ( // FormatJPG captures screenshots in JPEG format (smaller file size, lossy compression). FormatJPG ScreenshotFormat = "jpg" // FormatPNG captures screenshots in PNG format (larger file size, re-encoded from the JPEG capture). FormatPNG ScreenshotFormat = "png" // FormatWEBP captures screenshots in WebP format (modern format with good compression). FormatWEBP ScreenshotFormat = "webp" // FormatGIF captures screenshots in GIF format (single frame, indexed colour). FormatGIF ScreenshotFormat = "gif" )
Available image formats for screenshot capture.
type ScreenshotMetadata ¶
type ScreenshotMetadata struct {
// ExtensionName is the file extension (jpg, png, webp, gif).
ExtensionName string
// UpstreamStatusCode is the HTTP status code from the target website.
UpstreamStatusCode int
// UpstreamURL is the final URL after any redirects.
UpstreamURL string
}
ScreenshotMetadata contains metadata about a captured screenshot.
type ScreenshotOption ¶
type ScreenshotOption string
ScreenshotOption defines options to customize screenshot capture behavior.
const ( // OptionLoadImages enables image loading (disabled by default for performance). OptionLoadImages ScreenshotOption = "load_images" // OptionDarkMode enables dark mode rendering. OptionDarkMode ScreenshotOption = "dark_mode" // OptionBlockBanners blocks cookie banners and similar overlays. OptionBlockBanners ScreenshotOption = "block_banners" // OptionPrintMediaFormat uses print media CSS for rendering. OptionPrintMediaFormat ScreenshotOption = "print_media_format" )
Available options for customizing screenshot capture.
type ScreenshotResult ¶
type ScreenshotResult struct {
// Image contains the raw screenshot image bytes.
Image []byte
// Metadata contains information about the screenshot.
Metadata ScreenshotMetadata
// JobUUID is the job of a screenshot with a webhook: the image is delivered to the webhook, and Image and Metadata are empty.
JobUUID string
}
ScreenshotResult represents a screenshot captured by the API.
func (*ScreenshotResult) Save ¶
func (s *ScreenshotResult) Save(name string, savePath ...string) (string, error)
Save saves a screenshot result to disk.
Parameters:
- name: The base name for the file (without extension)
- savePath: Optional directory path where to save the file (defaults to current directory)
Returns the full path to the saved file.
Example:
filePath, err := s.Save("example", "./screenshots")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Screenshot saved to: %s\n", filePath)
type SpiderUsage ¶
type Subscription ¶
type Subscription struct {
Billing SubscriptionBilling `json:"billing"`
ExtraScrapeAllowed bool `json:"extra_scrape_allowed"`
MaxConcurrency int `json:"max_concurrency"`
Period SubscriptionPeriod `json:"period"`
PlanName string `json:"plan_name"`
Usage SubscriptionUsage `json:"usage"`
}
type SubscriptionBilling ¶
type SubscriptionBilling struct {
CurrentExtraScrapeRequestPrice SubscriptionIntegerPrice `json:"current_extra_scrape_request_price"`
ExtraScrapeRequestPricePer10k SubscriptionFloatPrice `json:"extra_scrape_request_price_per_10k"`
OngoingPayment SubscriptionFloatPrice `json:"ongoing_payment"`
PlanPrice SubscriptionIntegerPrice `json:"plan_price"`
}
type SubscriptionFloatPrice ¶
type SubscriptionPeriod ¶
type SubscriptionUsage ¶
type SubscriptionUsage struct {
Spider SpiderUsage `json:"spider"`
Schedule ScheduleUsage `json:"schedule"`
Scrape ScrapeUsage `json:"scrape"`
}
type URIContext ¶
type URIContext struct {
BaseURL string `json:"base_url"`
Fragment interface{} `json:"fragment"`
Host string `json:"host"`
Params interface{} `json:"params"`
Port int `json:"port"`
Query interface{} `json:"query"`
RootDomain string `json:"root_domain"`
Scheme string `json:"scheme"`
}
URIContext contains parsed URI information about the requested URL.
type UnblockConfig ¶
type UnblockConfig struct {
URL string `json:"url"`
Country string `json:"country,omitempty"`
OS string `json:"os,omitempty"` // Fingerprint OS: linux, windows, macos, android, iphone, ipad
BrowserBrand string `json:"browser_brand,omitempty"` // Fingerprint browser brand: chrome, edge, brave, opera
Session string `json:"session,omitempty"` // Named session for reconnection — reuses an existing unblocker session and disables auto-close
Timeout int `json:"timeout,omitempty"` // Navigation timeout in seconds
BrowserTimeout int `json:"browser_timeout,omitempty"` // Browser session timeout in seconds
EnableMCP bool `json:"enable_mcp,omitempty"` // Enable MCP support in the browser
Debug bool `json:"debug,omitempty"` // Record the session for replay via CloudBrowserPlayback / CloudBrowserVideo
}
UnblockConfig configures an unblock request.
type UnblockResult ¶
type UnblockResult struct {
WSURL string `json:"ws_url"`
SessionID string `json:"session_id"`
RunID string `json:"run_id"`
MCPEndpoint string `json:"mcp_endpoint,omitempty"` // MCP streamable-HTTP endpoint (only when EnableMCP=true)
}
UnblockResult is the response from the /unblock endpoint.
type UpdateScheduleRequest ¶ added in v0.3.4
type UpdateScheduleRequest struct {
Recurrence *ScheduleRecurrence `json:"recurrence,omitempty"`
ScheduledDate *string `json:"scheduled_date,omitempty"`
AllowConcurrency *bool `json:"allow_concurrency,omitempty"`
RetryOnFailure *bool `json:"retry_on_failure,omitempty"`
MaxRetries *int `json:"max_retries,omitempty"`
Notes *string `json:"notes,omitempty"`
ScrapeConfig map[string]interface{} `json:"scrape_config,omitempty"`
ScreenshotConfig map[string]interface{} `json:"screenshot_config,omitempty"`
CrawlerConfig map[string]interface{} `json:"crawler_config,omitempty"`
}
type VerifyAPIKeyResult ¶
type VerifyAPIKeyResult struct {
// Valid indicates whether the API key is valid.
Valid bool `json:"valid"`
}
VerifyAPIKeyResult represents the result of an API key verification.
type VisionDeficiencyType ¶
type VisionDeficiencyType string
const ( VisionDeficiencyTypeNone VisionDeficiencyType = "none" VisionDeficiencyTypeDeuteranopia VisionDeficiencyType = "deuteranopia" VisionDeficiencyTypeProtanopia VisionDeficiencyType = "protanopia" VisionDeficiencyTypeTritanopia VisionDeficiencyType = "tritanopia" VisionDeficiencyTypeAchromatopsia VisionDeficiencyType = "achromatopsia" VisionDeficiencyTypeBlurredVision VisionDeficiencyType = "blurredVision" VisionDeficiencyTypeReducedContrast VisionDeficiencyType = "reducedContrast" )
func (VisionDeficiencyType) AnyEnum ¶
func (f VisionDeficiencyType) AnyEnum() []any
func (VisionDeficiencyType) Enum ¶
func (f VisionDeficiencyType) Enum() []VisionDeficiencyType
func (VisionDeficiencyType) IsValid ¶
func (f VisionDeficiencyType) IsValid() bool
func (VisionDeficiencyType) String ¶
func (f VisionDeficiencyType) String() string
type WaitOptions ¶
type WaitOptions struct {
// PollInterval controls how often to hit the status endpoint.
// Defaults to 5 seconds when zero.
PollInterval time.Duration
// MaxWait is the total wall-clock deadline for the wait loop.
// Zero means "no timeout" — wait indefinitely.
MaxWait time.Duration
// Verbose enables per-poll progress logging via the default SDK logger.
Verbose bool
// AllowCancelled, when true, makes Wait return nil instead of
// ErrCrawlerCancelled when the crawler reaches the CANCELLED terminal
// state. Useful for the cancel-then-wait pattern where the caller
// already triggered the cancellation themselves. Defaults to false,
// preserving the prior return-error behavior for callers that observe
// external interrupts.
AllowCancelled bool
}
WaitOptions configures the polling behavior of Crawl.Wait.
type WarcPage ¶
WarcPage is a simplified view of a single crawled page extracted from a WARC artifact. Use it when you don't need the raw record / WARC headers.
type WarcParser ¶
type WarcParser struct {
// contains filtered or unexported fields
}
WarcParser walks a WARC byte stream record-by-record.
The parser handles both gzip-compressed and uncompressed WARC data and supports the subset of the WARC 1.0 format that the Scrapfly Crawler produces in its artifacts. It is intentionally minimal — for general-purpose WARC consumption, prefer a dedicated library like github.com/nlnwa/gowarc.
Example:
artifact, _ := client.CrawlArtifact(uuid, scrapfly.ArtifactTypeWARC)
parser, err := scrapfly.ParseWARC(artifact.Data)
if err != nil { log.Fatal(err) }
pages, _ := parser.GetPages()
for _, page := range pages {
fmt.Printf("%s: %d bytes\n", page.URL, len(page.Content))
}
func ParseWARC ¶
func ParseWARC(data []byte) (*WarcParser, error)
ParseWARC creates a WarcParser from raw WARC bytes.
Auto-detects gzip-compressed input by checking the magic bytes (1f 8b). Returns a non-nil error only when the gzip header is present but the payload fails to decompress.
func (*WarcParser) GetPages ¶
func (p *WarcParser) GetPages() ([]WarcPage, error)
GetPages returns every HTTP response in the WARC as a slim WarcPage.
This is the easiest way to walk a crawler's artifact without dealing with the WARC format directly. For very large artifacts, use IterResponses instead so you can stream records one at a time.
func (*WarcParser) IterRecords ¶
func (p *WarcParser) IterRecords(fn func(*WarcRecord) bool) (int, error)
IterRecords walks every record in the WARC stream and invokes fn for each successfully parsed record. Iteration stops when fn returns false (treat the bool as "continue", not "ok").
Returns the number of records yielded and any error encountered while reading the underlying byte stream.
func (*WarcParser) IterResponses ¶
func (p *WarcParser) IterResponses(fn func(*WarcRecord) bool) (int, error)
IterResponses is a convenience helper that yields only HTTP response records (record_type=response) with a non-zero status code.
type WarcRecord ¶
type WarcRecord struct {
// RecordType is the value of the WARC-Type header (e.g. "response", "request",
// "metadata", "warcinfo").
RecordType string
// URL is the value of the WARC-Target-URI header.
URL string
// Headers contains the parsed HTTP response headers (only populated for
// "response" records). Header names are kept in their original casing.
Headers map[string]string
// Content is the raw record body. For "response" records, this is the HTTP
// response body (after the headers section); for other types, this is the
// raw content block as it appeared in the WARC.
Content []byte
// StatusCode is the parsed HTTP status code for "response" records.
// Zero for non-response records or when the status line couldn't be parsed.
StatusCode int
// WARCHeaders contains all the WARC-level headers (WARC-Type, WARC-Date, etc.).
WARCHeaders map[string]string
}
WarcRecord represents a single WARC record parsed from a crawl artifact.
Mirrors the dataclass exposed by the Python SDK's `WarcRecord`.
Source Files
¶
- alert.go
- batch.go
- classify.go
- client.go
- cloud_browser.go
- cloud_browser_downloads.go
- config_crawler.go
- config_extraction.go
- config_scrape.go
- config_screenshot.go
- crawl.go
- crawler.go
- doc.go
- enums.go
- errors.go
- har_utils.go
- logger.go
- monitoring.go
- result_account.go
- result_crawler.go
- result_scrape.go
- result_screenshot.go
- schedule.go
- unblocker.go
- utils.go
- warc_utils.go
Directories
¶
| Path | Synopsis |
|---|---|
|
batch
command
Scrape multiple URLs in a single request using the Batch Scraping API.
|
Scrape multiple URLs in a single request using the Batch Scraping API. |
|
batch/msgpack
command
Use msgpack wire encoding for per-part bodies in a batch.
|
Use msgpack wire encoding for per-part bodies in a batch. |
|
batch/proxified
command
Mix proxified and JSON-envelope scrapes in a single batch.
|
Mix proxified and JSON-envelope scrapes in a single batch. |
|
cloud_browser
command
|
|
|
Package scenario provides a fluent builder for creating Scrapfly API JS Scenarios.
|
Package scenario provides a fluent builder for creating Scrapfly API JS Scenarios. |