Class Spider

All Implemented Interfaces:
AutoCloseable

public class Spider extends ChilkatObject
<section class="spider-summary">

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.

</section>

Event-capable: long-running methods report progress through a ProgressListener installed with setProgressListener(ProgressListener), onAbortCheck(BooleanSupplier), onPercentDone(IntPredicate) or onProgressInfo(BiConsumer).

Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when done; an unclosed instance is freed when it becomes unreachable.

See Also:
Online reference
  • Constructor Details

    • Spider

      public Spider()
      Creates a new Spider object.
  • Method Details

    • getAbortCurrent

      public boolean getAbortCurrent()
      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.)
      Returns:
      the value of the AbortCurrent property
    • setAbortCurrent

      public void setAbortCurrent​(boolean value)
      Sets the AbortCurrent property; see getAbortCurrent().
      Parameters:
      value - the new value
    • getAvoidHttps

      public boolean getAvoidHttps()
      If set the 1 (true) the spider will avoid all HTTPS URLs. The default is 0 (false).
      Returns:
      the value of the AvoidHttps property
    • setAvoidHttps

      public void setAvoidHttps​(boolean value)
      Sets the AvoidHttps property; see getAvoidHttps().
      Parameters:
      value - the new value
    • getCacheDir

      public String getCacheDir()
      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.
      Returns:
      the value of the CacheDir property
    • setCacheDir

      public void setCacheDir​(String value)
      Sets the CacheDir property; see getCacheDir().
      Parameters:
      value - the new value (not null)
    • getChopAtQuery

      public boolean getChopAtQuery()
      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).
      Returns:
      the value of the ChopAtQuery property
    • setChopAtQuery

      public void setChopAtQuery​(boolean value)
      Sets the ChopAtQuery property; see getChopAtQuery().
      Parameters:
      value - the new value
    • getConnectTimeout

      public int getConnectTimeout()
      The maximum number of seconds to wait while connecting to an HTTP server.
      Returns:
      the value of the ConnectTimeout property
    • setConnectTimeout

      public void setConnectTimeout​(int value)
      Sets the ConnectTimeout property; see getConnectTimeout().
      Parameters:
      value - the new value
    • getDomain

      public String getDomain()
      The domain name that is being spidered. This is the domain previously set in the Initialize method.
      Returns:
      the value of the Domain property (read-only)
    • getFetchFromCache

      public boolean getFetchFromCache()
      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.
      Returns:
      the value of the FetchFromCache property
    • setFetchFromCache

      public void setFetchFromCache​(boolean value)
      Sets the FetchFromCache property; see getFetchFromCache().
      Parameters:
      value - the new value
    • getFinalRedirectUrl

      public String getFinalRedirectUrl()
      If the last URL crawled was redirected (as indicated by the WasRedirected property), this property will contain the final redirect URL.
      Returns:
      the value of the FinalRedirectUrl property (read-only)
    • getHeartbeatMs

      public int getHeartbeatMs()
      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.
      Returns:
      the value of the HeartbeatMs property
    • setHeartbeatMs

      public void setHeartbeatMs​(int value)
      Sets the HeartbeatMs property; see getHeartbeatMs().
      Parameters:
      value - the new value
    • getLastFromCache

      public boolean getLastFromCache()
      Equal to 1 if the last page spidered was fetched from the cache. Otherwise equal to 0.
      Returns:
      the value of the LastFromCache property (read-only)
    • getLastHtml

      public String getLastHtml()
      The HTML text of the last paged fetched by the spider.
      Returns:
      the value of the LastHtml property (read-only)
    • getLastHtmlDescription

      public String getLastHtmlDescription()
      The HTML META description from the last page fetched by the spider.
      Returns:
      the value of the LastHtmlDescription property (read-only)
    • getLastHtmlKeywords

      public String getLastHtmlKeywords()
      The HTML META keywords from the last page fetched by the spider.
      Returns:
      the value of the LastHtmlKeywords property (read-only)
    • getLastHtmlTitle

      public String getLastHtmlTitle()
      The HTML title from the last page fetched by the spider.
      Returns:
      the value of the LastHtmlTitle property (read-only)
    • getLastModDateStr

      public String getLastModDateStr()
      The last modification date/time (RFC822 format) from the last page fetched by the spider.
      Returns:
      the value of the LastModDateStr property (read-only)
    • getLastUrl

      public String getLastUrl()
      The URL of the last page spidered.
      Returns:
      the value of the LastUrl property (read-only)
    • getMaxResponseSize

      public int getMaxResponseSize()
      The maximum HTTP response size allowed. The spider will automatically fail any pages larger than this size. The default value is 250,000 bytes.
      Returns:
      the value of the MaxResponseSize property
    • setMaxResponseSize

      public void setMaxResponseSize​(int value)
      Sets the MaxResponseSize property; see getMaxResponseSize().
      Parameters:
      value - the new value
    • getMaxUrlLen

      public int getMaxUrlLen()
      The maximum URL length allowed. URLs longer than this are not added to the unspidered list. The default value is 200.
      Returns:
      the value of the MaxUrlLen property
    • setMaxUrlLen

      public void setMaxUrlLen​(int value)
      Sets the MaxUrlLen property; see getMaxUrlLen().
      Parameters:
      value - the new value
    • getNumAvoidPatterns

      public int getNumAvoidPatterns()
      The number of avoid patterns previously set by calling AddAvoidPattern.
      Returns:
      the value of the NumAvoidPatterns property (read-only)
    • getNumFailed

      public int getNumFailed()
      The number of URLs in the object's failed URL list.
      Returns:
      the value of the NumFailed property (read-only)
    • getNumOutboundLinks

      public int getNumOutboundLinks()
      The number of URLs in the object's outbound links URL list.
      Returns:
      the value of the NumOutboundLinks property (read-only)
    • getNumSpidered

      public int getNumSpidered()
      The number of URLs in the object's already-spidered URL list.
      Returns:
      the value of the NumSpidered property (read-only)
    • getNumUnspidered

      public int getNumUnspidered()
      The number of URLs in the object's unspidered URL list.
      Returns:
      the value of the NumUnspidered property (read-only)
    • getPreferIpv6

      public boolean getPreferIpv6()
      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.
      Returns:
      the value of the PreferIpv6 property
    • setPreferIpv6

      public void setPreferIpv6​(boolean value)
      Sets the PreferIpv6 property; see getPreferIpv6().
      Parameters:
      value - the new value
    • getProxyDomain

      public String getProxyDomain()
      The domain name of a proxy host if an HTTP proxy is used.
      Returns:
      the value of the ProxyDomain property
    • setProxyDomain

      public void setProxyDomain​(String value)
      Sets the ProxyDomain property; see getProxyDomain().
      Parameters:
      value - the new value (not null)
    • getProxyLogin

      public String getProxyLogin()
      If an HTTP proxy is used and it requires authentication, this property specifies the HTTP proxy login.
      Returns:
      the value of the ProxyLogin property
    • setProxyLogin

      public void setProxyLogin​(String value)
      Sets the ProxyLogin property; see getProxyLogin().
      Parameters:
      value - the new value (not null)
    • getProxyPassword

      public String getProxyPassword()
      If an HTTP proxy is used and it requires authentication, this property specifies the HTTP proxy password.
      Returns:
      the value of the ProxyPassword property
    • setProxyPassword

      public void setProxyPassword​(String value)
      Sets the ProxyPassword property; see getProxyPassword().
      Parameters:
      value - the new value (not null)
    • getProxyPort

      public int getProxyPort()
      The port number of a proxy server if an HTTP proxy is used.
      Returns:
      the value of the ProxyPort property
    • setProxyPort

      public void setProxyPort​(int value)
      Sets the ProxyPort property; see getProxyPort().
      Parameters:
      value - the new value
    • getReadTimeout

      public int getReadTimeout()
      The maximum number of seconds to wait when reading from an HTTP server.
      Returns:
      the value of the ReadTimeout property
    • setReadTimeout

      public void setReadTimeout​(int value)
      Sets the ReadTimeout property; see getReadTimeout().
      Parameters:
      value - the new value
    • getUpdateCache

      public boolean getUpdateCache()
      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.
      Returns:
      the value of the UpdateCache property
    • setUpdateCache

      public void setUpdateCache​(boolean value)
      Sets the UpdateCache property; see getUpdateCache().
      Parameters:
      value - the new value
    • getUserAgent

      public String getUserAgent()
      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.
      Returns:
      the value of the UserAgent property
    • setUserAgent

      public void setUserAgent​(String value)
      Sets the UserAgent property; see getUserAgent().
      Parameters:
      value - the new value (not null)
    • getWasRedirected

      public boolean getWasRedirected()
      Indicates whether the last URL crawled was redirected. (true = yes, false = no)
      Returns:
      the value of the WasRedirected property (read-only)
    • getWindDownCount

      public int getWindDownCount()
      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.
      Returns:
      the value of the WindDownCount property
    • setWindDownCount

      public void setWindDownCount​(int value)
      Sets the WindDownCount property; see getWindDownCount().
      Parameters:
      value - the new value
    • addAvoidOutboundLinkPattern

      public void addAvoidOutboundLinkPattern​(String 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.
      Parameters:
      pattern - the pattern argument (not null)
    • addAvoidPattern

      public void addAvoidPattern​(String 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.
      Parameters:
      pattern - the pattern argument (not null)
    • addMustMatchPattern

      public void addMustMatchPattern​(String 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.
      Parameters:
      pattern - the pattern argument (not null)
    • addUnspidered

      public void addUnspidered​(String 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.
      Parameters:
      url - the url argument (not null)
    • canonicalizeUrl

      public String canonicalizeUrl​(String 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.

      Parameters:
      url - the url argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • clearFailedUrls

      public void clearFailedUrls()
      Clears the object's internal list of URLs that could not be downloaded.
    • clearOutboundLinks

      public void clearOutboundLinks()
      Clears the object's internal list of outbound URLs that will automatically accumulate while spidering.
    • clearSpideredUrls

      public void clearSpideredUrls()
      Clears the object's internal list of already-spidered URLs that will automatically accumulate while spidering.
    • crawlNext

      public boolean 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 false. Information about the URL crawled is available in the properties LastUrl, LastFromCache, and LastModDate.

      Returns:
      the result; this method never throws ChilkatException
    • fetchRobotsText

      public String 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:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getAvoidPattern

      public String getAvoidPattern​(int index)
      Returns the Nth avoid pattern previously added by calling AddAvoidPattern. Indexing begins at 0.
      Parameters:
      index - the index argument
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getBaseDomain

      public String getBaseDomain​(String 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.
      Parameters:
      domain - the domain argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getFailedUrl

      public String getFailedUrl​(int index)
      Returns the Nth URL in the failed URL list. Indexing begins at 0.
      Parameters:
      index - the index argument
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getOutboundLink

      public String getOutboundLink​(int index)
      Returns the Nth URL in the outbound link URL list. Indexing begins at 0.
      Parameters:
      index - the index argument
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getSpideredUrl

      public String getSpideredUrl​(int index)
      Returns the Nth URL in the already-spidered URL list. Indexing begins at 0.
      Parameters:
      index - the index argument
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getUnspideredUrl

      public String getUnspideredUrl​(int index)
      Returns the Nth URL in the unspidered URL list. Indexing begins at 0.
      Parameters:
      index - the index argument
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getUrlDomain

      public String getUrlDomain​(String 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.
      Parameters:
      url - the url argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • initialize

      public void initialize​(String 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.
      Parameters:
      domain - the domain argument (not null)
    • recrawlLast

      public boolean 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.
      Returns:
      the result; this method never throws ChilkatException
    • skipUnspidered

      public void skipUnspidered​(int index)
      Moves a URL from the unspidered list to the spidered list. This allows an application to skip a specific URL.
      Parameters:
      index - the index argument
    • sleepMs

      public void sleepMs​(int numMilliseconds)
      Suspends the execution of the current thread until the time-out interval elapses.
      Parameters:
      numMilliseconds - the numMilliseconds argument
    • setProgressListener

      public void setProgressListener​(ProgressListener listener)
      Installs the listener that receives this object's progress events (abortCheck, percentDone, progressInfo) during its long-running methods; replaces any listener or lambda installed before; null removes it.
      Parameters:
      listener - the listener, or null
      Throws:
      IllegalStateException - if called from inside one of this object's own callbacks
    • getProgressListener

      public ProgressListener getProgressListener()
      Returns the installed listener, or null.
      Returns:
      the listener installed with setProgressListener(ProgressListener) or one of the on... methods
    • onAbortCheck

      public void onAbortCheck​(BooleanSupplier callback)
      Installs a listener whose only callback is abortCheck: called every HeartbeatMs milliseconds during a long-running method; return true to abort it. Replaces any listener installed before.
      Parameters:
      callback - the callback, or null to remove the listener
    • onPercentDone

      public void onPercentDone​(IntPredicate callback)
      Installs a listener whose only callback is percentDone: called with the completion percentage (0..100) as a long-running method progresses; return true to abort it. Replaces any listener installed before.
      Parameters:
      callback - the callback, or null to remove the listener
    • onProgressInfo

      public void onProgressInfo​(BiConsumer<String,​String> callback)
      Installs a listener whose only callback is progressInfo: called with a name/value pair of progress information as a long-running method proceeds. Replaces any listener installed before.
      Parameters:
      callback - the callback, or null to remove the listener