Spider Chilkat2 Perl Reference Documentation
Chilkat2::Spider
Current Version: 11.7.0
Markdown version of this page for AI tools (v 11.7.0) · all AI docs
Chilkat.Spider
Initialize the spider with a domain and crawl only URLs that belong to
that same domain.
Add starting URLs, crawl the next queued URL, skip selected URLs, and
inspect unspidered, spidered, failed, and outbound URL lists.
Add wildcard avoid patterns, must-match patterns, and outbound-link
avoid patterns to control which URLs are crawled or collected.
Read the last fetched HTML, page title, meta description, meta keywords,
final redirect URL, and last-modified timestamp.
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.
Configure user-agent, proxy settings, connect/read timeouts, IPv6
preference, maximum URL length, maximum response size, and abort support.
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
URL queue management
Filtering rules
Page metadata
Caching and redirects
Network controls
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.
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
use Chilkat2;
my $spider = Chilkat2::Spider->new;
# or set properties (and RaiseError) at creation:
# my $spider = Chilkat2::Spider->new(VerboseLogging => 1, RaiseError => 1);Creates the object. The optional pairs set writable properties (and RaiseError) in order, as if set one by one; an unknown or read-only name croaks. use Chilkat2; loads every class; the Chilkat2/Spider.pm file holds only this class's documentation (perldoc Chilkat2::Spider).
Perl frees the object when its last reference goes (undef $spider, or the variable going out of scope); there is nothing to close. Objects returned by methods are independent and freed the same way. The class may be subclassed (use parent -norequire, 'Chilkat2::Spider';): an object is a blessed hash reference whose hash is free for the subclass's own fields.
When false (the default), a method that fails returns false (or undef), and the reason is in LastErrorText. When true, it dies with a Chilkat2::Error instead, as DBI does with its RaiseError. Objects returned by a method inherit the value of the object that returned them.
Errors
A Chilkat2::Error stringifies to the failed call's full LastErrorText, and has the methods text, class ('Chilkat2::Spider'), method (the method name) and object. Methods that look something up and find nothing return undef without dying (each such method says so), methods that answer a question (HasMember, IsUnlocked, ...) return a plain boolean, and property reads and writes never fail for Chilkat reasons.
Misuse always croaks, with your file and line, whatever RaiseError is: a wrong number of arguments, a reference or undef where a string or number is expected, an object of the wrong class, an out-of-range integer, a string containing a NUL character, a wide character in a byte string, or a write to a read-only property.
Strings are Perl character strings in both directions (length, regexes and :encoding layers see characters); binary data (BinData) is a byte string. Unlocking: call Chilkat2::Global->new->UnlockBundle('...') once at startup.
Properties
AbortCurrent
my $boolVal = $spider->AbortCurrent;
$spider->AbortCurrent($boolVal);
When set to 1, 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 0 when the next method is called. When the abort occurs, this property is reset to 0. Both synchronous and asynchronous method calls can be aborted. (A synchronous method call could be aborted by setting this property from a separate thread.)
AvoidHttps
my $boolVal = $spider->AvoidHttps;
$spider->AvoidHttps($boolVal);
If set the 1 (true) the spider will avoid all HTTPS URLs. The default is 0 (false).
topCacheDir
my $strVal = $spider->CacheDir;
$spider->CacheDir($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.
ChopAtQuery
my $boolVal = $spider->ChopAtQuery;
$spider->ChopAtQuery($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).
topConnectTimeout
my $intVal = $spider->ConnectTimeout;
$spider->ConnectTimeout($intVal);
The maximum number of seconds to wait while connecting to an HTTP server.
topDebugLogFilePath
my $strVal = $spider->DebugLogFilePath;
$spider->DebugLogFilePath($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.
Domain
my $strVal = $spider->Domain;
The domain name that is being spidered. This is the domain previously set in the Initialize method.
topFetchFromCache
my $boolVal = $spider->FetchFromCache;
$spider->FetchFromCache($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.
FinalRedirectUrl
my $strVal = $spider->FinalRedirectUrl;
If the last URL crawled was redirected (as indicated by the WasRedirected property), this property will contain the final redirect URL.
topHeartbeatMs
my $intVal = $spider->HeartbeatMs;
$spider->HeartbeatMs($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.
LastErrorHtml
my $strVal = $spider->LastErrorHtml;
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.
topLastErrorText
my $strVal = $spider->LastErrorText;
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.
LastErrorXml
my $strVal = $spider->LastErrorXml;
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.
topLastFromCache
my $boolVal = $spider->LastFromCache;
Equal to 1 if the last page spidered was fetched from the cache. Otherwise equal to 0.
topLastHtml
my $strVal = $spider->LastHtml;
The HTML text of the last paged fetched by the spider.
topLastHtmlDescription
my $strVal = $spider->LastHtmlDescription;
The HTML META description from the last page fetched by the spider.
LastHtmlKeywords
my $strVal = $spider->LastHtmlKeywords;
LastHtmlTitle
my $strVal = $spider->LastHtmlTitle;
LastMethodSuccess
my $boolVal = $spider->LastMethodSuccess;
$spider->LastMethodSuccess($boolVal);
Indicates the success or failure of the most recent method call: 1 means success, 0 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.
LastModDateStr
my $strVal = $spider->LastModDateStr;
The last modification date/time (RFC822 format) from the last page fetched by the spider.
topLastUrl
my $strVal = $spider->LastUrl;
The URL of the last page spidered.
topMaxResponseSize
my $intVal = $spider->MaxResponseSize;
$spider->MaxResponseSize($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.
MaxUrlLen
my $intVal = $spider->MaxUrlLen;
$spider->MaxUrlLen($intVal);
The maximum URL length allowed. URLs longer than this are not added to the unspidered list. The default value is 200.
NumAvoidPatterns
my $intVal = $spider->NumAvoidPatterns;
The number of avoid patterns previously set by calling AddAvoidPattern.
topNumFailed
my $intVal = $spider->NumFailed;
The number of URLs in the object's failed URL list.
topNumOutboundLinks
my $intVal = $spider->NumOutboundLinks;
The number of URLs in the object's outbound links URL list.
topNumSpidered
my $intVal = $spider->NumSpidered;
The number of URLs in the object's already-spidered URL list.
topNumUnspidered
my $intVal = $spider->NumUnspidered;
PreferIpv6
my $boolVal = $spider->PreferIpv6;
$spider->PreferIpv6($boolVal);
If 1, then use IPv6 over IPv4 when both are supported for a particular domain. The default value of this property is 0, which will choose IPv4 over IPv6.
ProxyDomain
my $strVal = $spider->ProxyDomain;
$spider->ProxyDomain($strVal);
The domain name of a proxy host if an HTTP proxy is used.
topProxyLogin
my $strVal = $spider->ProxyLogin;
$spider->ProxyLogin($strVal);
If an HTTP proxy is used and it requires authentication, this property specifies the HTTP proxy login.
topProxyPassword
my $strVal = $spider->ProxyPassword;
$spider->ProxyPassword($strVal);
If an HTTP proxy is used and it requires authentication, this property specifies the HTTP proxy password.
topProxyPort
my $intVal = $spider->ProxyPort;
$spider->ProxyPort($intVal);
The port number of a proxy server if an HTTP proxy is used.
topReadTimeout
my $intVal = $spider->ReadTimeout;
$spider->ReadTimeout($intVal);
The maximum number of seconds to wait when reading from an HTTP server.
topUpdateCache
my $boolVal = $spider->UpdateCache;
$spider->UpdateCache($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.
UserAgent
my $strVal = $spider->UserAgent;
$spider->UserAgent($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.
topVerboseLogging
my $boolVal = $spider->VerboseLogging;
$spider->VerboseLogging($boolVal);
If set to 1, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is 0. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
my $strVal = $spider->Version;
WasRedirected
my $boolVal = $spider->WasRedirected;
Indicates whether the last URL crawled was redirected. (1 = yes, 0 = no)
WindDownCount
my $intVal = $spider->WindDownCount;
$spider->WindDownCount($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.
Methods
AddAvoidOutboundLinkPattern
$spider->AddAvoidOutboundLinkPattern($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.
Returns the object, so calls can be chained.
AddAvoidPattern
$spider->AddAvoidPattern($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.
Returns the object, so calls can be chained.
AddMustMatchPattern
$spider->AddMustMatchPattern($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.
Returns the object, so calls can be chained.
AddUnspidered
$spider->AddUnspidered($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.
Returns the object, so calls can be chained.
CanonicalizeUrl
# $str is a string or undef
my $str = $spider->CanonicalizeUrl($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 undef on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
ClearFailedUrls
Clears the object's internal list of URLs that could not be downloaded.
Returns the object, so calls can be chained.
topClearOutboundLinks
Clears the object's internal list of outbound URLs that will automatically accumulate while spidering.
Returns the object, so calls can be chained.
topClearSpideredUrls
Clears the object's internal list of already-spidered URLs that will automatically accumulate while spidering.
Returns the object, so calls can be chained.
topCrawlNext
my $flag = $spider->CrawlNext();
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 0. Information about the URL crawled is available in the properties LastUrl, LastFromCache, and LastModDate.
Never dies: false is an answer, not a failure.
FetchRobotsText
my $str = $spider->FetchRobotsText();
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 undef on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
GetAvoidPattern
# $str is a string or undef
my $str = $spider->GetAvoidPattern($index);
Returns the Nth avoid pattern previously added by calling AddAvoidPattern. Indexing begins at 0.
Returns undef on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
GetBaseDomain
# $str is a string or undef
my $str = $spider->GetBaseDomain($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 undef on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
GetFailedUrl
# $str is a string or undef
my $str = $spider->GetFailedUrl($index);
Returns the Nth URL in the failed URL list. Indexing begins at 0.
Returns undef on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
GetOutboundLink
# $str is a string or undef
my $str = $spider->GetOutboundLink($index);
Returns the Nth URL in the outbound link URL list. Indexing begins at 0.
Returns undef on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
GetSpideredUrl
# $str is a string or undef
my $str = $spider->GetSpideredUrl($index);
Returns the Nth URL in the already-spidered URL list. Indexing begins at 0.
Returns undef on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
GetUnspideredUrl
# $str is a string or undef
my $str = $spider->GetUnspideredUrl($index);
Returns the Nth URL in the unspidered URL list. Indexing begins at 0.
Returns undef on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
GetUrlDomain
# $str is a string or undef
my $str = $spider->GetUrlDomain($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 undef on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
Initialize
$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.
Returns the object, so calls can be chained.
RecrawlLast
my $flag = $spider->RecrawlLast();
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.
Never dies: false is an answer, not a failure.
topSkipUnspidered
$spider->SkipUnspidered($index);
Moves a URL from the unspidered list to the spidered list. This allows an application to skip a specific URL.
Returns the object, so calls can be chained.
topSleepMs
$spider->SleepMs($numMilliseconds);
Suspends the execution of the current thread until the time-out interval elapses.
Returns the object, so calls can be chained.
topEvents
All Chilkat methods are synchronous: the call returns when the work is done. During a long-running call, Chilkat2::Spider reports progress to handlers installed with on, which takes Event => CODE pairs (closures, so a handler can use the variables around it):
$spider->on(
PercentDone => sub { my ($pctDone) = @_; print "$pctDone%\n"; return 0 }, # a true return aborts
ProgressInfo => sub { my ($name, $value) = @_; print "$name: $value\n" },
);
$spider->HeartbeatMs(250); # the AbortCheck handler is called 4 times per secondInstalls the handlers given, replacing those installed before for the same events; undef instead of a CODE reference removes one, and $spider->on() with no arguments returns the installed handlers as a list of pairs. The event names are checked: a misspelled one croaks, and nothing is installed.
The AbortCheck handler is called at the interval set by the HeartbeatMs property (0, the default, disables it); PercentDone is called when an operation's completion percentage is known; ProgressInfo delivers named progress values. A true return from the AbortCheck or PercentDone handler aborts the running method, which then fails in the usual way (false or undef, or a Chilkat2::Error under RaiseError).
Handlers run during the method call, on the thread that called it. Inside a handler, other objects may be used, but calling a method of the same object (or its on) croaks. A die in a handler aborts the running method and is re-thrown from the method call; the object remains usable. A handler that uses $spider itself makes a reference cycle: weaken the captured copy (Scalar::Util) or remove the handler when done.
AbortCheck
$spider->on(AbortCheck => sub { ... });
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.
Example
my $deadline = time() + 30; # give up after 30 seconds
$spider->HeartbeatMs(250); # call the handler 4 times per second
$spider->on(AbortCheck => sub { return time() > $deadline });PercentDone
$spider->on(PercentDone => sub { ... });
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 1. This will cause the method to terminate and return a failure status or corresponding failure value.
Example
$spider->on(PercentDone => sub {
my ($pctDone) = @_; # 0 to 100
print "Percent done: $pctDone\n";
return 0; # return a true value to abort the method in progress
});ProgressInfo
$spider->on(ProgressInfo => sub { ... });
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.
Example
$spider->on(ProgressInfo => sub {
my ($name, $value) = @_;
print "$name: $value\n";
});