Spider Lua Reference Documentation

chilkat.Spider

Current Version: 11.7.0

Markdown version of this page for AI tools (v 11.7.0) · all AI docs

Chilkat.Spider

Crawl a website domain, manage URL queues, filter links, cache pages, and inspect fetched HTML.

Chilkat.Spider crawls pages within a single initialized domain. It maintains internal lists of unspidered, spidered, failed, and outbound URLs; fetches one page at a time; extracts same-domain links for continued crawling; collects outbound links separately; respects robots.txt; supports wildcard include and avoid patterns; can use a dedicated cache directory; and exposes the last fetched HTML, title, meta description, keywords, redirect information, cache status, and last-modified date.

Domain-limited crawling

Initialize the spider with a domain and crawl only URLs that belong to that same domain.

URL queue management

Add starting URLs, crawl the next queued URL, skip selected URLs, and inspect unspidered, spidered, failed, and outbound URL lists.

Filtering rules

Add wildcard avoid patterns, must-match patterns, and outbound-link avoid patterns to control which URLs are crawled or collected.

Page metadata

Read the last fetched HTML, page title, meta description, meta keywords, final redirect URL, and last-modified timestamp.

Caching and redirects

Fetch pages from a Chilkat-managed cache, update the cache, detect when a page was redirected, and inspect whether the last page came from cache.

Network controls

Configure user-agent, proxy settings, connect/read timeouts, IPv6 preference, maximum URL length, maximum response size, and abort support.

Common pattern: Call Initialize with the target domain, add one or more starting URLs with AddUnspidered, optionally add filtering patterns, then repeatedly call CrawlNext. After each successful crawl, inspect LastUrl, LastHtml, page metadata, redirect state, and the URL-list counts to decide whether to continue, skip, recrawl, or process the page.
Scope note: Spider is intended for controlled, domain-oriented crawling and link discovery. Use Chilkat.Http or Chilkat.Rest when the task is a single HTTP request, API call, form post, or download rather than a crawl of discovered links.

Object Creation

local chilkat = require("chilkat")

local spider = chilkat.Spider.new()
local spider = chilkat.Spider.new()

Creates the object (chilkat.Spider() does the same). Lua's garbage collector frees it when it is no longer referenced; spider:dispose() frees it at once, and in Lua 5.4 and later local spider <close> = chilkat.Spider.new() frees it when the block ends. Calling a method of a disposed object raises an error.

Errors

A method that fails returns nil followed by the error text, as io.open does: local body, err = spider:method(...), where err is the object's last_error_text. Wrap the call in assert() to raise an error with that text instead. Methods that answer a question return true or false, numbers are returned as they are (check last_method_success where the description says a value means failure), and property reads and writes never fail for Chilkat reasons.

Misuse raises a Lua error: a wrong argument type or a missing argument (bad argument #1 to ...), an unknown property name, a write to a read-only property, an out-of-range integer, or an object of the wrong class.

Names are Chilkat's in snake_case: QuickGetStr is quick_get_str, LastErrorText is last_error_text. Properties are fields (spider.verbose_logging = true) and methods use the colon (spider:method(...)). Strings are UTF-8; binary data is a Lua string of bytes. Indexes are 0-based, as in every Chilkat API. Unlocking: call chilkat.unlock_bundle("...") once at startup.

Properties

AbortCurrent
-- boolVal is a boolean
local boolVal = spider.abort_current
spider.abort_current = boolVal
Introduced in version 9.5.0.58

When set to true, causes the currently running method to abort. Methods that always finish quickly (i.e.have no length file operations or network communications) are not affected. If no method is running, then this property is automatically reset to false when the next method is called. When the abort occurs, this property is reset to false. Both synchronous and asynchronous method calls can be aborted. (A synchronous method call could be aborted by setting this property from a separate thread.)

top
AvoidHttps
-- boolVal is a boolean
local boolVal = spider.avoid_https
spider.avoid_https = boolVal

If set the 1 (true) the spider will avoid all HTTPS URLs. The default is 0 (false).

top
CacheDir
-- strVal is a string
local strVal = spider.cache_dir
spider.cache_dir = strVal

Specifies a cache directory to use for spidering. If either of the FetchFromCache or UpdateCache properties are true, this is the location of the cache to be used. Note: the Internet Explorer, Netscape, and FireFox caches are completely separate from the Chilkat Spider cache directory. You should specify a new and empty directory.

More Information and Examples
top
ChopAtQuery
-- boolVal is a boolean
local boolVal = spider.chop_at_query
spider.chop_at_query = boolVal

If equal to 1 (true), then the query portion of all URLs are automatically removed when adding to the unspidered list. The default value is 0 (false).

top
ConnectTimeout
-- intVal is an integer
local intVal = spider.connect_timeout
spider.connect_timeout = intVal

The maximum number of seconds to wait while connecting to an HTTP server.

top
DebugLogFilePath
-- strVal is a string
local strVal = spider.debug_log_file_path
spider.debug_log_file_path = strVal

If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.

Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.

Possible causes of hangs include:

  • A timeout property set to 0, indicating an infinite timeout.
  • A hang occurring within an event callback in the application code.
  • An internal bug in the Chilkat code causing the hang.

More Information and Examples
top
Domain
-- strVal is a string (read-only)
local strVal = spider.domain

The domain name that is being spidered. This is the domain previously set in the Initialize method.

top
FetchFromCache
-- boolVal is a boolean
local boolVal = spider.fetch_from_cache
spider.fetch_from_cache = boolVal

If equal to 1 (true) then pages are fetched from cache when possible. If 0, the cache is ignored. The default value is 1. Regardless, if no CacheDir is set then the cache is not used.

More Information and Examples
top
FinalRedirectUrl
-- strVal is a string (read-only)
local strVal = spider.final_redirect_url
Introduced in version 9.5.0.85

If the last URL crawled was redirected (as indicated by the WasRedirected property), this property will contain the final redirect URL.

top
HeartbeatMs
-- intVal is an integer
local intVal = spider.heartbeat_ms
spider.heartbeat_ms = intVal

The interval in milliseconds between each AbortCheck event callback, which enables an application to abort certain method calls before they complete. By default, HeartbeatMs is set to 0, meaning no AbortCheck event callbacks will trigger.

More Information and Examples
top
LastErrorHtml
-- strVal is a string (read-only)
local strVal = spider.last_error_html

Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorText
-- strVal is a string (read-only)
local strVal = spider.last_error_text

Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorXml
-- strVal is a string (read-only)
local strVal = spider.last_error_xml

Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastFromCache
-- boolVal is a boolean (read-only)
local boolVal = spider.last_from_cache

Equal to 1 if the last page spidered was fetched from the cache. Otherwise equal to 0.

top
LastHtml
-- strVal is a string (read-only)
local strVal = spider.last_html

The HTML text of the last paged fetched by the spider.

top
LastHtmlDescription
-- strVal is a string (read-only)
local strVal = spider.last_html_description

The HTML META description from the last page fetched by the spider.

More Information and Examples
top
LastHtmlKeywords
-- strVal is a string (read-only)
local strVal = spider.last_html_keywords

The HTML META keywords from the last page fetched by the spider.

More Information and Examples
top
LastHtmlTitle
-- strVal is a string (read-only)
local strVal = spider.last_html_title

The HTML title from the last page fetched by the spider.

More Information and Examples
top
LastMethodSuccess
-- boolVal is a boolean
local boolVal = spider.last_method_success
spider.last_method_success = boolVal

Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.

top
LastModDateStr
-- strVal is a string (read-only)
local strVal = spider.last_mod_date_str

The last modification date/time (RFC822 format) from the last page fetched by the spider.

top
LastUrl
-- strVal is a string (read-only)
local strVal = spider.last_url

The URL of the last page spidered.

top
MaxResponseSize
-- intVal is an integer
local intVal = spider.max_response_size
spider.max_response_size = intVal

The maximum HTTP response size allowed. The spider will automatically fail any pages larger than this size. The default value is 250,000 bytes.

More Information and Examples
top
MaxUrlLen
-- intVal is an integer
local intVal = spider.max_url_len
spider.max_url_len = intVal

The maximum URL length allowed. URLs longer than this are not added to the unspidered list. The default value is 200.

More Information and Examples
top
NumAvoidPatterns
-- intVal is an integer (read-only)
local intVal = spider.num_avoid_patterns

The number of avoid patterns previously set by calling AddAvoidPattern.

top
NumFailed
-- intVal is an integer (read-only)
local intVal = spider.num_failed

The number of URLs in the object's failed URL list.

top
NumOutboundLinks
-- intVal is an integer (read-only)
local intVal = spider.num_outbound_links

The number of URLs in the object's outbound links URL list.

top
NumSpidered
-- intVal is an integer (read-only)
local intVal = spider.num_spidered

The number of URLs in the object's already-spidered URL list.

top
NumUnspidered
-- intVal is an integer (read-only)
local intVal = spider.num_unspidered

The number of URLs in the object's unspidered URL list.

More Information and Examples
top
PreferIpv6
-- boolVal is a boolean
local boolVal = spider.prefer_ipv6
spider.prefer_ipv6 = boolVal

If true, then use IPv6 over IPv4 when both are supported for a particular domain. The default value of this property is false, which will choose IPv4 over IPv6.

top
ProxyDomain
-- strVal is a string
local strVal = spider.proxy_domain
spider.proxy_domain = strVal

The domain name of a proxy host if an HTTP proxy is used.

top
ProxyLogin
-- strVal is a string
local strVal = spider.proxy_login
spider.proxy_login = strVal

If an HTTP proxy is used and it requires authentication, this property specifies the HTTP proxy login.

top
ProxyPassword
-- strVal is a string
local strVal = spider.proxy_password
spider.proxy_password = strVal

If an HTTP proxy is used and it requires authentication, this property specifies the HTTP proxy password.

top
ProxyPort
-- intVal is an integer
local intVal = spider.proxy_port
spider.proxy_port = intVal

The port number of a proxy server if an HTTP proxy is used.

top
ReadTimeout
-- intVal is an integer
local intVal = spider.read_timeout
spider.read_timeout = intVal

The maximum number of seconds to wait when reading from an HTTP server.

top
UpdateCache
-- boolVal is a boolean
local boolVal = spider.update_cache
spider.update_cache = boolVal

If equal to 1 (true) then pages saved to the cache. If 0, the cache is ignored. The default value is 1. Regardless, if no CacheDir is set then the cache is not used.

More Information and Examples
top
UserAgent
-- strVal is a string
local strVal = spider.user_agent
spider.user_agent = strVal

The value of the HTTP user-agent header field to be sent with HTTP requests. This can be set to any desired value, but be aware that some websites may reject requests from unknown user agents.

top
VerboseLogging
-- boolVal is a boolean
local boolVal = spider.verbose_logging
spider.verbose_logging = boolVal

If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.

top
Version
-- strVal is a string (read-only)
local strVal = spider.version

Version of the component/library, such as "10.1.0"

More Information and Examples
top
WasRedirected
-- boolVal is a boolean (read-only)
local boolVal = spider.was_redirected
Introduced in version 9.5.0.85

Indicates whether the last URL crawled was redirected. (true = yes, false = no)

top
WindDownCount
-- intVal is an integer
local intVal = spider.wind_down_count
spider.wind_down_count = intVal

The wind-down phase begins when this number of URLs has been spidered. When in the wind-down phase, no new URLs are added to the unspidered list. The default value is 0 which means that there is NO wind-down phase.

top

Methods

AddAvoidOutboundLinkPattern
-- pattern is a string
spider:add_avoid_outbound_link_pattern(pattern)

Adds a wildcarded pattern to prevent collecting matching outbound link URLs. For example, if *google* is added, then any outbound links containing the word google will be ignored. The * character matches zero or more of any character.

More Information and Examples
top
AddAvoidPattern
-- pattern is a string
spider:add_avoid_pattern(pattern)

Adds a wildcarded pattern to prevent spidering matching URLs. For example, if *register* is added, then any url containing the word register is not spidered. The * character matches zero or more of any character.

More Information and Examples
top
AddMustMatchPattern
-- pattern is a string
spider:add_must_match_pattern(pattern)

Adds a wildcarded pattern to limit spidering to only URLs that match the pattern. For example, if */products/* is added, then only URLs containing /products/ are spidered. This is helpful for only spidering a portion of a website. The * character matches zero or more of any character.

More Information and Examples
top
AddUnspidered
-- url is a string
spider:add_unspidered(url)

To begin spidering you must call this method one or more times to provide starting points. It adds a single URL to the object's internal queue of URLs to be spidered.

More Information and Examples
top
CanonicalizeUrl
-- url is a string
-- str is a string, or nil and err on failure
local str, err = spider:canonicalize_url(url)

Canonicalizes a URL by doing the following:

  • Drops username/password if present.
  • Drops fragment if present.
  • Converts domain to lowercase.
  • Removes port 80 or 443
  • Remove default.asp, index.html, index.htm, default.html, index.htm, default.htm, index.php, index.asp, default.php, .cfm, .aspx, ,php3, .pl, .cgi, .txt, .shtml, .phtml
  • Remove www. from the domain if present.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
ClearFailedUrls
spider:clear_failed_urls()

Clears the object's internal list of URLs that could not be downloaded.

top
ClearOutboundLinks
spider:clear_outbound_links()

Clears the object's internal list of outbound URLs that will automatically accumulate while spidering.

top
ClearSpideredUrls
spider:clear_spidered_urls()

Clears the object's internal list of already-spidered URLs that will automatically accumulate while spidering.

top
CrawlNext
-- flag is true or false
local flag = spider:crawl_next()

Crawls the next URL in the internal list of unspidered URLs. The URL is moved from the unspidered list to the spidered list. Any new links within the same domain and not yet spidered are added to the unspidered list. (providing that they do not match avoid patterns, etc.) Any new outbound links are added to the outbound URL list. If successful, the HTML of the downloaded page is available in the LastHtml property. If there are no more URLs left unspidered, the method returns false. Information about the URL crawled is available in the properties LastUrl, LastFromCache, and LastModDate.

Returns true or false: an answer, not a success flag.

More Information and Examples
top
FetchRobotsText
-- str is a string, or nil and err on failure
local str, err = spider:fetch_robots_text()

Returns the contents of the robots.txt file from the domain being crawled. This spider object will not crawl URLs excluded by robots.txt. If you believe the spider is not behaving correctly, please notify us at support@chilkatsoft.com and provide information detailing a case that allows us to reproduce the problem.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
GetAvoidPattern
-- index is an integer
-- str is a string, or nil and err on failure
local str, err = spider:get_avoid_pattern(index)

Returns the Nth avoid pattern previously added by calling AddAvoidPattern. Indexing begins at 0.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
GetBaseDomain
-- domain is a string
-- str is a string, or nil and err on failure
local str, err = spider:get_base_domain(domain)

Returns the second-level + top-level domain of the domain. For example, if domain is xyz.example.com, this returns example.com. For some domains, such as xyz.example.co.uk, the top 3 levels are returned, such as example.co.uk.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
GetFailedUrl
-- index is an integer
-- str is a string, or nil and err on failure
local str, err = spider:get_failed_url(index)

Returns the Nth URL in the failed URL list. Indexing begins at 0.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
GetOutboundLink
-- index is an integer
-- str is a string, or nil and err on failure
local str, err = spider:get_outbound_link(index)

Returns the Nth URL in the outbound link URL list. Indexing begins at 0.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
GetSpideredUrl
-- index is an integer
-- str is a string, or nil and err on failure
local str, err = spider:get_spidered_url(index)

Returns the Nth URL in the already-spidered URL list. Indexing begins at 0.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
GetUnspideredUrl
-- index is an integer
-- str is a string, or nil and err on failure
local str, err = spider:get_unspidered_url(index)

Returns the Nth URL in the unspidered URL list. Indexing begins at 0.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
GetUrlDomain
-- url is a string
-- str is a string, or nil and err on failure
local str, err = spider:get_url_domain(url)

Returns the domain name part of a URL. For example, if the URL is https://www.chilkatsoft.com/test.asp, then www.chilkatsoft.com is returned.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
Initialize
-- domain is a string
spider:initialize(domain)

Initializes the object to begin spidering a domain. Calling Initialize clears any patterns added via the AddAvoidOutboundLinkPattern, AddAvoidPattern, and AddMustMatchPattern methods. The domain name passed to this method is what is returned by the Domain property. The spider only crawls URLs within the same domain.

More Information and Examples
top
RecrawlLast
-- flag is true or false
local flag = spider:recrawl_last()

Re-crawls the last URL spidered. This helpful when cookies set in a previous page load cause the page to be loaded differently the next time.

Returns true or false: an answer, not a success flag.

top
SkipUnspidered
-- index is an integer
spider:skip_unspidered(index)

Moves a URL from the unspidered list to the spidered list. This allows an application to skip a specific URL.

top
SleepMs
-- num_milliseconds is an integer
spider:sleep_ms(num_milliseconds)

Suspends the execution of the current thread until the time-out interval elapses.

top

Events

All Chilkat methods are synchronous: the call returns when the work is done. During a long-running call, chilkat.Spider reports progress to the functions given to set_event_handler, in a table keyed by event name (plain functions, not methods: closures carry whatever state they need):

spider:set_event_handler({
    percent_done  = function(pct) print(pct .. "%") end,              -- return true to abort
    progress_info = function(name, value) print(name, value) end,
})
spider.heartbeat_ms = 250   -- abort_check is called 4 times per second
spider:set_event_handler({ event_name = function(...) ... end, ... })

Installs the handlers, replacing any installed before; spider:set_event_handler(nil) removes them. The event names are checked when the table is installed: a misspelled one raises an error.

The abort_check handler is called at the interval set by the heartbeat_ms property (0, the default, disables it); percent_done is called when an operation's completion percentage is known; progress_info delivers named progress values. A true return from abort_check or percent_done aborts the running method, which then fails in the usual way (nil, err). An error raised in a handler aborts the method and is raised again from the method call; the object remains usable.

AbortCheck
-- handler: function() ... return abort end -- a true return aborts the method in progress
spider:set_event_handler({ abort_check = function() ... end })

Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.

More Information and Examples

Example

local deadline = os.time() + 30                  -- give up after 30 seconds
spider.heartbeat_ms = 250                      -- call the handler 4 times per second
spider:set_event_handler({ abort_check = function() return os.time() > deadline end })
top
PercentDone
-- handler: function(pct_done) ... return abort end -- a true return aborts
spider:set_event_handler({ percent_done = function(pct_done) ... end })

This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pctDone argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pctDone equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).

The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.

To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.

More Information and Examples

Example

spider:set_event_handler({
    percent_done = function(pct_done)     -- 0 to 100
        print("Percent done: " .. pct_done)
        return false                       -- return true to abort the method in progress
    end,
})
top
ProgressInfo
-- handler: function(name, value) ... end
spider:set_event_handler({ progress_info = function(name, value) ... end })

This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.

Note: Some Chilkat methods don't fire any ProgressInfo events.

More Information and Examples

Example

spider:set_event_handler({
    progress_info = function(name, value) print(name .. ": " .. value) end,
})
top