crawler

package
v0.22.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: AGPL-3.0 Imports: 23 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MarshalValidatorRules

func MarshalValidatorRules(rules *ValidatorRules) (string, error)

MarshalValidatorRules serializes rules to a JSON string for storage.

Types

type Crawler

type Crawler interface {
	Crawl(ctx context.Context, startURL string, v *Validator) (<-chan *document.Document, error)
	Close() error
}

Crawler is the public interface for scraping backends. Crawl performs a BFS traversal starting from startURL, sending discovered documents to the returned channel. The channel is closed when crawling finishes or ctx is cancelled. Close must be called when the Crawler is no longer needed to release backend resources.

func New

func New(cfg *config.CrawlerConfig, robots *RobotsCache, opts ...Option) (Crawler, error)

New creates a Crawler backed by the backend specified in cfg.Backend. Accepted values are "chromedp" and "http" (default). Pass a non-nil RobotsCache to enforce robots.txt rules during crawling; pass nil to disable robots.txt checks entirely.

type HTTPClient

type HTTPClient struct {
	*http.Client
	// contains filtered or unexported fields
}

HTTPClient applies configured headers and a user agent to GET requests.

func NewHTTPClient

func NewHTTPClient(cfg *config.CrawlerConfig) (*HTTPClient, error)

NewHTTPClient configures HTTP transport, cookies, headers, and timeout for crawlers and importers. The caller handles backend options.

func (*HTTPClient) Get

func (c *HTTPClient) Get(ctx context.Context, rawURL string) (*http.Response, error)

Get sends a GET request with the configured request headers and context. The caller must close the response body.

type Option

type Option func(*options)

Option customizes crawler traversal behavior.

func WithSkipURLChecker

func WithSkipURLChecker(skipURLChecker SkipURLChecker) Option

WithSkipURLChecker installs a prefetch skip predicate. It runs after validator and robots checks, but before configured crawl delay and network fetch.

type PersistentCrawler

type PersistentCrawler struct {
	// contains filtered or unexported fields
}

PersistentCrawler persists traversal and document processing outcomes so interrupted jobs can resume without skipping unacknowledged documents.

func NewPersistent

func NewPersistent(cfg *config.CrawlerConfig, jobID string, robots *RobotsCache, opts ...Option) (*PersistentCrawler, error)

NewPersistent creates a crawler that persists its state to the database. jobID is used as the primary key for the crawl job. Pass a non-nil RobotsCache to enforce robots.txt rules; pass nil to disable.

func (*PersistentCrawler) Close

func (c *PersistentCrawler) Close() error

Close releases resources held by the underlying fetcher backend.

func (*PersistentCrawler) Crawl

func (c *PersistentCrawler) Crawl(ctx context.Context, startURL string, v *Validator, process func(*document.Document) error) error

Crawl starts (or resumes) the persistent crawl job identified by jobID. It calls process synchronously for each fetched document and marks its source URL done only after process succeeds. Processing failures are recorded against the source URL and crawling continues. Cancellation leaves unfinished work available for resume. A process crash can cause a successful submission to be retried if its completion was not yet recorded. startURL and v are only used when creating a new job; on resume the stored start URL and validator rules take precedence (the caller is responsible for passing the correct v with a pre-seeded visited counter).

type RobotsCache

type RobotsCache struct {
	// contains filtered or unexported fields
}

RobotsCache fetches and caches robots.txt files in memory for the lifetime of a crawl. It is safe for concurrent use.

func NewRobotsCache

func NewRobotsCache(userAgent string) *RobotsCache

NewRobotsCache creates a RobotsCache that will identify itself using the given userAgent when fetching robots.txt files.

func NewRobotsCacheWithProxy

func NewRobotsCacheWithProxy(userAgent, proxy string) (*RobotsCache, error)

NewRobotsCacheWithProxy creates a RobotsCache that uses proxy for robots.txt requests. The proxy accepts the same URL formats as crawler backends.

func (*RobotsCache) Allowed

func (r *RobotsCache) Allowed(ctx context.Context, rawURL string) bool

Allowed reports whether the given URL is allowed to be fetched according to the site's robots.txt. If the robots.txt cannot be fetched it is treated as permissive (all URLs allowed) to avoid blocking legitimate crawls due to transient network errors. Oversized files block the origin for this crawl.

type SkipURLChecker

type SkipURLChecker func(rawURL string) (bool, error)

SkipURLChecker decides whether rawURL should be skipped before delay and fetch.

type URLStatus

type URLStatus int

URLStatus indicates what the crawler should do with a given URL.

const (
	// URLAllow means the URL should be fetched and indexed.
	URLAllow URLStatus = iota
	// URLSkip means this URL should be skipped but crawling continues.
	URLSkip
	// URLStop means crawling should stop entirely.
	URLStop
)

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

Validator decides whether a URL should be crawled based on ValidatorRules. It is safe for concurrent use.

func NewValidator

func NewValidator(rules *ValidatorRules) (*Validator, error)

NewValidator compiles the regexp patterns in rules and returns a Validator.

func (*Validator) Rules

func (v *Validator) Rules() *ValidatorRules

Rules returns the ValidatorRules used to create this Validator. The returned pointer must not be mutated.

func (*Validator) SetVisited

func (v *Validator) SetVisited(n int)

SetVisited pre-seeds the visited counter (used when resuming a job).

func (*Validator) Validate

func (v *Validator) Validate(u *url.URL, depth int) URLStatus

Validate checks whether u at the given crawl depth should be visited. When URLAllow is returned the internal visited counter is incremented, so the same Validator instance tracks how many pages have been allowed.

type ValidatorRules

type ValidatorRules struct {
	// MaxDepth is the maximum link depth to follow from the start URL.
	// 0 means unlimited.
	MaxDepth int
	// MaxLinks is the maximum total number of pages to visit.
	// 0 means unlimited.
	MaxLinks int
	// AllowedDomains restricts crawling to these hostnames (and their
	// subdomains). Empty means allow all domains.
	AllowedDomains []string
	// ExcludeDomains lists hostnames (and their subdomains) to skip.
	ExcludeDomains []string
	// AllowedPatterns lists regexp patterns; only URLs matching at least
	// one are followed. Empty means allow all URLs.
	AllowedPatterns []string
	// ExcludePatterns lists regexp patterns; URLs matching any are skipped.
	ExcludePatterns []string
	// NoDepth disables traversal beyond URLs explicitly inserted into the crawl
	// queue. Discovered links are ignored instead of enqueued.
	NoDepth bool
}

ValidatorRules configures the traversal constraints for a crawl. Zero values mean unlimited / no restriction for numeric fields and empty slices mean "allow all" for list fields.

func UnmarshalValidatorRules

func UnmarshalValidatorRules(s string) (*ValidatorRules, error)

UnmarshalValidatorRules deserializes rules from a JSON string.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL