colibri

package module
v0.0.0-...-b1083d3 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2024 License: MIT Imports: 11 Imported by: 0

README

Colibri

Colibri is an extensible web crawling and scraping framework for Go, used to crawl and extract structured data on the web.

See webextractor.

Installation

 $ go get github.com/gonzxlez/colibri

Do

// Do makes an HTTP request based on the rules.
func (c *Colibri) Do(rules *Rules) (resp Response, err error) 
var rawRules = []byte(`{...}`) // Raw Rules ~ JSON 

c := colibri.New()
c.Client = ...    // Required
c.Delay = ...     // Optional
c.RobotsTxt = ... // Optional
c.Parser = ...    // Optional

var rules colibri.Rules
err := json.Unmarshal(rawRules, &rules)
if err != nil {
	panic(err)
} 

resp, err := c.Do(rules)
if err != nil {
	panic(err)
}

fmt.Println("URL:", resp.URL())
fmt.Println("Status code:", resp.StatusCode())
fmt.Println("Content-Type", resp.Header().Get("Content-Type"))

Extract

// Extract makes the HTTP request and parses the content of the response based on the rules.
func (c *Colibri) Extract(rules *Rules) (output *Output, err error)
var rawRules = []byte(`{...}`) // Raw Rules ~ JSON 

c := colibri.New()
c.Client = ...    // Required
c.Delay = ...     // Optional
c.RobotsTxt = ... // Optional
c.Parser = ...    // Required

var rules colibri.Rules
err := json.Unmarshal(rawRules, &rules)
if err != nil {
	panic(err)
} 

output, err := c.Extract(&rules)
if err != nil {
	panic(err)
}

fmt.Println("URL:", output.Response.URL())
fmt.Println("Status code:", output.Response.StatusCode())
fmt.Println("Content-Type", output.Response.Header().Get("Content-Type"))
fmt.Println("Data:", output.Data)

Raw Rules ~ JSON

{
	"Method": "string",
	"URL": "string",
	"Proxy": "string",
	"Header": {
		"string": "string",
		"string": ["string", "string", ...]
	},
	"Timeout": "number_millisecond",
	"Cookies": "bool",
	"IgnoreRobotsTxt": "bool",
	"Delay": "number_millisecond",
	"Redirects": "number",
	"Selectors": {...}
}

Selectors

{
	"Selectors": {
		"key_name": "expression"
	}
}
{
	"Selectors": {
		"title": "//head/title"
	}
}
{
	"Selectors": {
		"key_name":  {
			"Expr": "expression",
			"Type": "expression_type",
			"All": "bool",
			"Follow": "bool",
			"Method": "string",
			"Header": {...},
			"Proxy": "string",
			"Timeout": "number_millisecond",
			"Selectors": {...}
		}
	}
}
{
	"Selectors": {
		"title":  {
			"Expr": "//head/title",
			"Type": "xpath"
		}
	}
}
Nested selectors
{
	"Selectors": {
		"body":  {
			"Expr": "//body",
			"Type": "xpath",
			"Selectors": {
				"p": "//p"
			}
		}
	}
}
Find all
{
	"Selectors": {
		"a":  {
			"Expr": "//body/a",
			"Type": "xpath",
			"All": true,
		}
	}
}
Follow URLs
{
	"Selectors": {
		"a":  {
			"Expr": "//body/a",
			"Type": "xpath",
			"All": true,
			"Follow": true,
			"Selectors": {
				"title": "//head/title"
			}
		}
	}
}
{
	"Selectors": {
		"a":  {
			"Expr": "//body/a",
			"Type": "xpath",
			"All": true,
			"Follow": true,
			"Proxy": "http://proxy-url.com:8080",
			"Cookies": true,
			"Selectors": {
				"title": "//head/title"
			}
		}
	}
}
Extra Fields
{
	"Selectors": {
		"title":  {
			"Expr": "//head/title",
			"Type": "xpath",
			
			"Required": true
		}
	}
}

Example

{
	"Method": "GET",
	"URL": "https://example.com",
	"Header": {
		"User-Agent": "test/0.1.0",
	},
	"Timeout": 5000,
	"Selectors": {
		"a":  {
			"Expr": "//body/a",
			"Type": "xpath",
			"All": true,
			"Follow": true,
			"Selectors": {
				"title": "//head/title"
			}
		}
	}
}

Documentation

Overview

Colibri is an extensible web crawling and scraping framework for Go, used to crawl and extract structured data on the web.

Index

Constants

View Source
const (
	KeyCookies = "cookies"

	KeyDelay = "delay"

	KeyHeader = "header"

	KeyIgnoreRobotsTxt = "ignoreRobotsTxt"

	KeyMethod = "method"

	KeyProxy = "proxy"

	KeyRedirects = "redirects"

	KeySelectors = "selectors"

	KeyTimeout = "timeout"

	KeyURL = "URL"
)
View Source
const (
	KeyAll = "all"

	KeyExpr = "expr"

	KeyFollow = "follow"

	KeyName = "name"

	KeyType = "type"
)
View Source
const DefaultUserAgent = "colibri/0.1"

DefaultUserAgent is the default User-Agent used for requests.

Variables

View Source
var (
	// ErrClientIsNil returned when Client is nil.
	ErrClientIsNil = errors.New("client is nil")

	// ErrParserIsNil returned when Parser is nil.
	ErrParserIsNil = errors.New("parser is nil")

	// ErrRulesIsNil returned when rules are nil.
	ErrRulesIsNil = errors.New("rules is nil")

	// ErrMaxRedirects are returned when the redirect limit is reached.
	ErrMaxRedirects = errors.New("max redirects limit reached")

	// ErrorRobotstxtRestriction is returned when the page cannot be accessed due to robots.txt restrictions.
	ErrorRobotstxtRestriction = errors.New("page not accessible due to robots.txt restriction")
)
View Source
var (
	// ErrInvalidHeader is returned when the value is an invalid header.
	ErrInvalidHeader = errors.New("invalid header")

	// ErrMustBeString is returned when the value is not a string.
	ErrMustBeString = errors.New("must be a string")

	// ErrMustBeNumber is returned when the value is not a number.
	ErrMustBeNumber = errors.New("must be a number")

	// ErrNotAssignable is returned when the value is not assignable to the field.
	ErrNotAssignable = errors.New("value is not assignable to field")
)
View Source
var (
	// ErrInvalidSelector is returned when the value is not a valid selector.
	ErrInvalidSelector = errors.New("invalid selector")

	// ErrInvalidSelectors is returned when the value is not a valid selector value.
	ErrInvalidSelectors = errors.New("invalid selectors")
)

Functions

func AddError

func AddError(errs error, key string, err error) error

AddError adds an error to the existing error set. If errs or err is null or the key is empty, no operation is performed. If errs is not of type *Err, a new error of type *Err is returned and the original error is stored with the key "#".

func ReleaseRules

func ReleaseRules(rules *Rules)

ReleaseRules clears and sends the rules to the rules pool.

func ReleaseSelector

func ReleaseSelector(selector *Selector)

ReleaseRules clears and sends the selector to the selector pool.

func ToURL

func ToURL(value any) (*url.URL, error)

ToURL converts a value to a *url.URL.

Types

type Client

type Client interface {
	// Do makes HTTP requests.
	Do(c *Colibri, rules *Rules) (Response, error)

	// Clear cleans the fields of the structure.
	Clear()
}

Client represents an HTTP client.

type Colibri

type Colibri struct {
	Client    Client
	Delay     Delay
	RobotsTxt RobotsTxt
	Parser    Parser
}

Colibri makes HTTP requests and parses the content of the response based on rules.

func New

func New() *Colibri

New returns a new empty Colibri structure.

func (*Colibri) Clear

func (c *Colibri) Clear()

Clear cleans the fields of the structure.

func (*Colibri) Do

func (c *Colibri) Do(rules *Rules) (resp Response, err error)

Do makes an HTTP request based on the rules.

func (*Colibri) Extract

func (c *Colibri) Extract(rules *Rules) (output *Output, err error)

Extract makes the HTTP request and parses the content of the response based on the rules.

type Delay

type Delay interface {
	// Wait waits for the previous HTTP request to the same URL and stores
	// the timestamp, then starts the calculated delay with the timestamp
	// and the specified duration of the delay.
	Wait(u *url.URL, duration time.Duration)

	// Done warns that an HTTP request has been made to the URL.
	Done(u *url.URL)

	// Stamp records the time at which the HTTP request to the URL was made.
	Stamp(u *url.URL)

	// Clear cleans the fields of the structure.
	Clear()
}

Delay manages the delay between each HTTP request.

type Errs

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

Errs is a structure that stores and manages errors.

func (*Errs) Add

func (errs *Errs) Add(key string, err error) *Errs

Add adds an error to the error set. If the key or error is null, no operation is performed. If there is already an error stored with the same key, the error is stored with the key + # + key number. Returns a pointer to the updated error structure.

func (*Errs) Error

func (errs *Errs) Error() string

Error returns a string representation of errors stored in JSON format.

func (*Errs) Get

func (errs *Errs) Get(key string) (err error, ok bool)

Get returns the error associated with a key and a boolean indicating whether the key exists. If the key does not exist, a null error and false are returned.

func (*Errs) MarshalJSON

func (errs *Errs) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON representation of the stored errors.

type Output

type Output struct {
	// Response to Request.
	Response Response

	// Data contains the data extracted by the selectors.
	Data map[string]any
}

func (*Output) MarshalJSON

func (out *Output) MarshalJSON() ([]byte, error)

func (*Output) Serializable

func (out *Output) Serializable() map[string]any

Serializable returns the value of the output as a map for easy storage or transmission.

type Parser

type Parser interface {
	// Match returns true if the Content-Type is supported by the parser.
	Match(contentType string) bool

	// Parse parses the response based on the rules.
	Parse(rules *Rules, resp Response) (map[string]any, error)

	// Clear cleans the fields of the structure.
	Clear()
}

Parser represents a parser of the response content.

type Response

type Response interface {
	// URL returns the URL of the request.
	URL() *url.URL

	// StatusCode returns the status code.
	StatusCode() int

	// Header returns the HTTP header of the response.
	Header() http.Header

	// Body returns the response body.
	Body() io.ReadCloser

	// Redirects returns the redirected URLs.
	Redirects() []*url.URL

	// Serializable returns the response value as a map for easy storage or transmission.
	Serializable() map[string]any

	// Do Colibri Do method wrapper.
	// Wraps the Colibri with which the HTTP response was obtained.
	Do(rules *Rules) (Response, error)

	// Extract Colibri Extract method wrapper.
	// Wraps the Colibri with which the HTTP response was obtained.
	Extract(rules *Rules) (*Output, error)
}

Response represents an HTTP response.

type RobotsTxt

type RobotsTxt interface {
	// IsAllowed verifies that the User-Agent can access the URL.
	IsAllowed(c *Colibri, rules *Rules) error

	// Clear cleans the fields of the structure.
	Clear()
}

RobotsTxt represents a robots.txt parser.

type Rules

type Rules struct {
	//  Method specifies the HTTP method (GET, POST, PUT, ...).
	Method string

	// URL specifies the URL of the request.
	URL *url.URL

	// Proxy specifies the URL of the proxy.
	Proxy *url.URL

	// Header contains the HTTP header.
	Header http.Header

	// Timeout specifies the time limit for the HTTP request.
	Timeout time.Duration

	// Cookies specifies whether the client should send and store Cookies.
	Cookies bool

	// IgnoreRobotsTxt specifies whether robots.txt should be ignored.
	IgnoreRobotsTxt bool

	// Delay specifies the delay time between requests.
	Delay time.Duration

	// Redirects specifies the maximum number of redirects.
	Redirects int

	// Selectors
	Selectors []*Selector

	// Extra stores additional data.
	Extra map[string]any
}

func (*Rules) Clear

func (rules *Rules) Clear()

Clear clears all fields from the rules.

Selectors are released, see the ReleaseSelector function.

func (*Rules) Clone

func (rules *Rules) Clone() *Rules

Clone returns a copy of the original rules.

Cloning the Extra field can cause errors, so you should avoid storing pointers.

func (*Rules) UnmarshalJSON

func (rules *Rules) UnmarshalJSON(b []byte) (err error)

type Selector

type Selector struct {
	// Name selector name.
	Name string

	// Expr stores the selector expression.
	Expr string

	// Type stores the type of the selector expression.
	Type string

	// All specifies whether all elements are to be found.
	All bool

	// Follow specifies whether the URLs found by the selector should be followed.
	Follow bool

	// Method specifies the HTTP method (GET, POST, PUT, ...).
	Method string

	// Proxy specifies the URL of the proxy.
	Proxy *url.URL

	// Header contains the HTTP header.
	Header http.Header

	// Timeout specifies the time limit for the HTTP request.
	Timeout time.Duration

	// Selectors nested selectors.
	Selectors []*Selector

	// Extra stores additional data.
	Extra map[string]any
}

func CloneSelectors

func CloneSelectors(selectors []*Selector) []*Selector

CloneSelectors clones the selectors.

func ReleaseSelectors

func ReleaseSelectors(selectors []*Selector) []*Selector

func (*Selector) Clear

func (sel *Selector) Clear()

Clear clears all fields in the selector.

Selectors are released, see the ReleaseSelector function.

func (*Selector) Clone

func (sel *Selector) Clone() *Selector

Clone returns a copy of the original selector.

Cloning the Extra field can cause errors, so you should avoid storing pointers.

func (*Selector) Rules

func (sel *Selector) Rules(src *Rules) *Rules

Rules returns a Rules with the Selector's data.

If the selector does not have a specified value for the Proxy, User-Agent, or Timeout fields, the values from the source rules are used.

The values for the Cookies, IgnoreRobotsTxt, Delay, Redirects fields are obtained from the source rules.

Directories

Path Synopsis
parsers is an interface that Colibri can use to parse the content of responses.
parsers is an interface that Colibri can use to parse the content of responses.
webextractor are default interfaces for Colibri ready to start crawling or extracting data on the web.
webextractor are default interfaces for Colibri ready to start crawling or extracting data on the web.

Jump to

Keyboard shortcuts

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