Documentation
¶
Overview ¶
Package scrapeland is a client for the scrape.land web data extraction API.
There are two ways in, and most Go programs want the first:
- Client.HTTPClient returns a *http.Client wired to the rotating gateway. Every request it makes exits from a fresh IP. Nothing else in your code has to change — hand it to any library that accepts an *http.Client.
- Client.Fetch / Extract / Batch / Search call the data API directly and return parsed results, for when you want structured data rather than a transport.
Control parameters (country, sticky session, protocol, latency ceiling) are encoded into the proxy username, so they work through the plain transport too:
pb_live_KEY-country-us-session-job42-protocol-socks5-maxlatency-3000
Zero dependencies: standard library only.
Index ¶
- Constants
- Variables
- func Bool(b bool) *bool
- type APIError
- type BatchResult
- type Client
- func (c *Client) Account(ctx context.Context) (map[string]any, error)
- func (c *Client) Batch(ctx context.Context, urls []string, o *Options) (*BatchResult, error)
- func (c *Client) BatchIter(ctx context.Context, urls []string, o *Options, yield func(Result) bool) error
- func (c *Client) Capabilities(ctx context.Context) (map[string]any, error)
- func (c *Client) Extract(ctx context.Context, target string, fields map[string]any, o *Options) (*Result, error)
- func (c *Client) Fetch(ctx context.Context, target string, o *Options) (*Result, error)
- func (c *Client) GetJob(ctx context.Context, id string) (*Job, error)
- func (c *Client) HTTPClient(o *Options) *http.Client
- func (c *Client) Jobs(ctx context.Context, limit int) ([]Job, error)
- func (c *Client) ProxyURL(o *Options) (*url.URL, error)
- func (c *Client) ProxyUsername(o *Options) string
- func (c *Client) Rank(ctx context.Context, target, query string, o *Options) (*RankResult, error)
- func (c *Client) Search(ctx context.Context, query string, o *Options) (*SearchResult, error)
- func (c *Client) SubmitJob(ctx context.Context, jobType string, params map[string]any) (*Job, error)
- type Job
- type Option
- type Options
- type RankResult
- type RankedLink
- type Result
- type SearchResult
Constants ¶
const ( // DefaultGateway is the forward proxy. Port 8080 is the long-standing // endpoint; 443 also serves the proxy for networks that filter 8080. DefaultGateway = "http://gateway.scrape.land:8080" // DefaultAPIBase is the data API — a different host from the proxy. DefaultAPIBase = "https://scrape.land" )
const BatchMaxURLs = 20
BatchMaxURLs is the server's per-call cap for Batch; BatchIter chunks by it.
Variables ¶
var ErrNoAPIKey = errors.New("scrapeland: api key required (pass it or set $SCRAPELAND_API_KEY)")
ErrNoAPIKey is returned by New when no key was passed and none is in the environment.
Functions ¶
Types ¶
type APIError ¶
APIError is a non-2xx response from the data API. Status is the HTTP code; Body is the (truncated) response body, which usually carries a JSON message; RetryAfter is the server's Retry-After, when it sent one. Branch on the kind with the Is* helpers or check Status directly:
var apiErr *scrapeland.APIError
if errors.As(err, &apiErr) && apiErr.IsRateLimited() { time.Sleep(apiErr.RetryAfter) }
func (*APIError) IsBadRequest ¶ added in v1.0.0
IsBadRequest reports a 400 — a malformed or contradictory request (a retry won't help).
func (*APIError) IsNotFound ¶ added in v1.0.0
IsNotFound reports a 404 — no such resource (e.g. an unknown job id).
func (*APIError) IsPaymentRequired ¶ added in v1.0.0
IsPaymentRequired reports a 402 — out of quota / prepaid credit, or key budget spent.
func (*APIError) IsRateLimited ¶ added in v1.0.0
IsRateLimited reports a 429 — too many requests; honor RetryAfter.
func (*APIError) IsServer ¶ added in v1.0.0
IsServer reports a 5xx — a transient server-side failure, usually worth retrying.
func (*APIError) IsUnauthorized ¶ added in v1.0.0
IsUnauthorized reports a 401 — the API key is missing, invalid, or revoked.
type BatchResult ¶
type BatchResult struct {
Results []Result `json:"results"`
}
BatchResult is the response from Batch: one entry per requested URL, in order.
type Client ¶
type Client struct {
APIKey string
Gateway string
APIBase string
// Defaults applied to every request; per-request Options override them.
Country string
Session string
Protocol string
MaxLatencyMS int
// Retries counts EXTRA attempts after the first (default 2). Backoff is the
// base delay, doubled per attempt.
Retries int
Backoff time.Duration
// HTTP is used for data API calls. It is NOT proxied — the data API is a
// normal HTTPS endpoint. Use HTTPClient for proxied traffic.
HTTP *http.Client
}
Client talks to the scrape.land gateway and data API. The zero value is not usable — construct it with New.
func New ¶
New builds a Client. apiKey falls back to $SCRAPELAND_API_KEY. Gateway and API base fall back to $SCRAPELAND_GATEWAY / $SCRAPELAND_API_BASE, then the public endpoints.
func (*Client) BatchIter ¶ added in v1.0.0
func (c *Client) BatchIter(ctx context.Context, urls []string, o *Options, yield func(Result) bool) error
BatchIter fetches or extracts any number of URLs, auto-chunking into BatchMaxURLs-sized Batch calls and invoking yield for each Result in input order as chunks complete — the streaming counterpart to Batch, so you can feed a slice of any size without holding every response in memory or tripping the 20-URL cap. yield returns false to stop early (the range-over-func convention, so this composes with `for r := range ...` on Go 1.23+). o applies to every URL, exactly like Batch. A failed chunk stops iteration and returns its error (the same *APIError as Batch).
err := c.BatchIter(ctx, urls, &scrapeland.Options{Fields: f}, func(r scrapeland.Result) bool {
save(r); return true
})
func (*Client) Capabilities ¶
Capabilities reports what this deployment supports. No API key required.
func (*Client) Extract ¶
func (c *Client) Extract(ctx context.Context, target string, fields map[string]any, o *Options) (*Result, error)
Extract pulls structured data from a page. fields maps a name to a CSS selector, an XPath string (leading "/"), or an object with css/xpath/attr/all. Pass nil fields and set Options.Prompt to use AI extraction instead.
func (*Client) HTTPClient ¶
HTTPClient returns an *http.Client whose every request exits from a fresh IP. Pass nil for o to use the client defaults.
c, _ := scrapeland.New(key)
res, err := c.HTTPClient(nil).Get("https://api.ipify.org")
Each call builds a fresh Transport, because the control parameters live in the proxy credentials — sharing one across different Options would silently apply the first caller's country and session to everyone else.
func (*Client) ProxyUsername ¶
ProxyUsername builds the proxy username: the API key plus control parameters. Per-request values in o override the client defaults.
func (*Client) Rank ¶ added in v1.0.0
Rank scores a page's links by how relevant each is to query, so you can pick which sub-pages to fetch next instead of crawling everything. Set o.TopK to cap the list and o.Model ("fast"/"smart") to choose the backend. It is stateless: it ranks the links a page already has and never fetches them.
AI transparency: if the ranking step fails, Rank still returns a result (no error) with the links in document order and RankResult.RankingError set — so check that field when the order matters. Requires the AI backend to be configured. Billed as one fetch plus the AI surcharge; a failed ranking bills only the fetch.
type Job ¶
type Job struct {
ID string `json:"id"`
Type string `json:"type"`
Status string `json:"status"`
Result json.RawMessage `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
Job is an async job record.
type Option ¶
type Option func(*Client)
Option configures a Client.
func WithAPIBase ¶
WithAPIBase overrides the data API base URL.
func WithCountry ¶
WithCountry sets a default exit country (ISO code, e.g. "us").
func WithHTTPClient ¶
WithHTTPClient supplies the client used for data API calls (timeouts, tracing).
func WithMaxLatency ¶
WithMaxLatency only uses upstreams faster than the given milliseconds.
func WithProtocol ¶
WithProtocol restricts the upstream protocol ("http", "https", "socks5").
func WithRetries ¶
WithRetries sets how many EXTRA attempts follow a failure.
func WithSession ¶
WithSession sets a default sticky-session id (same exit IP across requests).
type Options ¶
type Options struct {
Format string `json:"format,omitempty"` // "html" (default), "text", "markdown", "raw"
Country string `json:"country,omitempty"`
Session string `json:"session,omitempty"`
Protocol string `json:"protocol,omitempty"`
MaxLatency int `json:"max_latency,omitempty"`
Render bool `json:"render,omitempty"`
Device string `json:"device,omitempty"`
BlockResources bool `json:"block_resources,omitempty"`
Fingerprint bool `json:"fingerprint,omitempty"`
WaitFor string `json:"wait_for,omitempty"`
Headers bool `json:"headers,omitempty"`
Screenshot bool `json:"screenshot,omitempty"`
FullPage bool `json:"full_page,omitempty"`
SendHeaders map[string]string `json:"send_headers,omitempty"`
Cookies string `json:"cookies,omitempty"`
Method string `json:"method,omitempty"`
Body string `json:"body,omitempty"`
Actions []any `json:"actions,omitempty"`
Metadata bool `json:"metadata,omitempty"`
Links bool `json:"links,omitempty"`
// Extraction. Fields holds CSS/XPath selectors; Prompt drives AI extraction.
Fields map[string]any `json:"fields,omitempty"`
Prompt string `json:"prompt,omitempty"`
Schema any `json:"schema,omitempty"`
Model string `json:"model,omitempty"`
ExtractType string `json:"extract_type,omitempty"`
// TopK caps the list returned by Rank (rank only; ignored elsewhere).
TopK int `json:"top_k,omitempty"`
// Structured selects what a Prompt returns. Nil (the default) and true give a JSON
// object in Result.Data; false gives a plain-language reply in Result.Answer and
// leaves Data nil. A pointer so "unset" and "explicitly false" differ — use
// scrapeland.Bool(false) to ask for prose.
//
// Schema and ExtractType both pin a JSON shape and so imply structured output;
// combining either with Structured=Bool(false) is rejected with a 400.
Structured *bool `json:"structured,omitempty"`
// Search only.
Count int `json:"count,omitempty"`
}
Options are the per-request knobs shared by Fetch, Extract, Batch and Search. Every field is optional; the zero value means "use the client default, or the server default". It doubles as the request payload, which is why the json tags matter as much as the field names.
type RankResult ¶ added in v1.0.0
type RankResult struct {
URL string `json:"url"`
Status int `json:"status"`
Query string `json:"query"`
Links []RankedLink `json:"links"`
RankingError string `json:"ranking_error,omitempty"`
}
RankResult is the response from Rank. If the AI step failed, Links come back in document order (not ranked) and RankingError explains why — Rank returns no error in that case, so always check RankingError when the order matters.
type RankedLink ¶ added in v1.0.0
type RankedLink struct {
URL string `json:"url"`
Text string `json:"text"`
Score float64 `json:"score"`
Reason string `json:"reason"`
}
RankedLink is one link scored by Rank: Score is 0-1, Reason is a short rationale.
type Result ¶
type Result struct {
URL string `json:"url"`
Status int `json:"status"`
HTML string `json:"html,omitempty"`
Text string `json:"text,omitempty"`
Markdown string `json:"markdown,omitempty"`
Base64 string `json:"base64,omitempty"`
ContentType string `json:"content_type,omitempty"`
Screenshot string `json:"screenshot,omitempty"`
Data map[string]any `json:"data,omitempty"`
Answer string `json:"answer,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
Links []string `json:"links,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Error string `json:"error,omitempty"`
}
Result is one fetched page. Which body field is populated depends on Format.