CL-HTTP Chapter 14: W4 Web Walker


Reference Manual | Prev: Chapter 13. Dynamic Forms | Next: Chapter 15. HTML Parser


Contents

  1. 14.1 Overview
  2. 14.2 Activities
  3. 14.3 Constraints
  4. 14.4 Actions
  5. 14.5 Walking Programmatically

14.1 Overview

W4 is a constraint-guided web walker for Common Lisp. It provides a declarative framework for defining web crawling activities where constraints control which URLs to visit and actions determine what to do with each retrieved resource. The walker handles link extraction, recursive traversal, cycle detection, and the HTTP robot exclusion protocol.

W4 was described in the paper A Constraint-Based Web Walker (Mallery, Dynamic Objects Workshop, 1996).

The W4 package (:W4) uses ANSI-COMMON-LISP, WWW-UTILS, URL, and HTTP. It imports HTTP client internals for making requests and processing headers. The architecture separates concerns into three layers:

  1. Activities — Named, reusable walk configurations that bind constraints and actions together.
  2. Constraints — Composable predicates that determine whether a URL should be processed. Constraints are typed (circumstance, context, URL, DNS, header, resource, HTML) and can be combined with boolean logic.
  3. Actions — Operations performed on URLs that pass all constraints. Actions include tracing, HTML generation, link extraction, and user-defined processing.

14.2 Activities

An activity is a named, parameterized walk configuration. It specifies the constraints that filter URLs, the actions to perform on matching URLs, the walk operator, and a report stream. Activities can be defined statically with w4:define-activity or created dynamically with w4:with-activity.

Static Activity Definition

(w4:define-activity trace-walk
  :documentation "Trace web walking, reporting on REPORT-STREAM."
  :constraint-set ((no-cycles)
                   (depth 2)
                   (header-robots-allowed))
  :operator "user@example.com"
  :actions ((trace) (trace-headers) (generate-inferiors))
  :report-stream *standard-output*)

The :constraint-set lists the constraints applied to each URL before actions execute. The :actions list names the action types to perform in order. The special action generate-inferiors extracts links from the page and queues them for recursive walking.

Dynamic Activity with with-activity

(w4:with-activity ("my-walk"
                   (:report-stream '*standard-output*)
                   :constraints '((depth 3)
                                  (no-cycles)
                                  (url-host ("example.com")))
                   :actions '((trace)
                              (generate-inferiors)))
  (walk url activity))

w4:with-activity creates a temporary activity for the dynamic extent of its body, binding the variable activity. The first argument is a name string; the second is a plist of activity options. The :constraints and :actions keyword arguments override the static defaults.

Activity Management

(w4:intern-activity name)
Find a named activity. Returns nil if not found.
(w4:unintern-activity name)
Remove a named activity.

14.3 Constraints

Constraints are composable predicates that control which URLs are visited during a walk. Each constraint type is defined with w4:define-constraint-type, specifying its category, a constraint function, and an allocator for its arguments. The generic function w4:satisfies-p tests whether a URL satisfies a constraint or constraint set.

Constraint Categories

Circumstance Constraints
Boolean combinators that compose other constraints: not, or, and, if. These allow arbitrary boolean logic over constraint sets.
Context Constraints
Constraints on the walk state rather than the URL: depth limits recursive depth.
URL Constraints
Constraints on URL properties: no-cycles (skip already-visited URLs), url-scheme (match URL scheme), url-host (match hostname), url-referrer-host (match referring host), url-parent-subsumed-by-directory-path.
Header Constraints
Constraints on HTTP response headers: header-robots-allowed (honor robots.txt), header-content-type (match MIME type), header-last-modification (compare modification date).
Resource Constraints
Constraints on the retrieved resource content.
HTML Constraints
Constraints on parsed HTML content (head and body sections).

Defining Custom Constraints

(w4:define-constraint-type
  url-path-prefix
  (:url
    :documentation "Succeeds when the URL path starts with PREFIX.")
  (constraint activity url prefix)
  (declare (ignore constraint activity))
  (let ((path (url:path url)))
    (and path (eql 0 (search prefix path)))))

The first form after the name is the constraint descriptor: a category keyword (:url, :context, :circumstance, :header, :resource, :html-head, :html-body), optional :documentation, optional :class, and optional :allocator. The remaining forms are the constraint function body, which receives constraint, activity, url, and any constraint-specific arguments.

Composing Constraints

;; Walk only HTML pages on two hosts, up to depth 3
:constraints '((depth 3)
               (no-cycles)
               (or (url-host ("www.example.com"))
                   (url-host ("docs.example.com")))
               (header-content-type (:text :html))
               (header-robots-allowed))

14.4 Actions

Actions define what happens when a URL passes all constraints. Action types are defined with w4:define-action-type and come in three classes:

Standard Actions (:standard)
Perform an operation on the URL and return. Examples: trace (print walk progress), trace-headers (print response headers), html-write-headers (write headers as HTML).
Encapsulating Actions (:encapsulating)
Wrap subsequent actions in a context. Examples: html-with-section (wrap in a section heading), html-with-paragraph (wrap in a paragraph), html-with-enumeration (wrap in a list). The body calls call-next-action to invoke the enclosed actions.
Generator Actions (:generator)
Produce new URLs to walk. The primary generator is generate-inferiors, which extracts links from the current page and queues them for recursive walking. generate-sorted-inferiors does the same with a sort predicate.

Defining Custom Actions

(w4:define-action-type
  save-page
  (:standard
    :documentation "Save the retrieved page to a local directory.")
  (action activity url directory)
  (declare (ignore action))
  (let ((headers (get-resource-headers activity url))
        (pathname (merge-pathnames (url:path url) directory)))
    (ensure-directories-exist pathname)
    (with-open-file (stream pathname :direction :output
                            :if-exists :supersede)
      ;; Write retrieved content to file
      ...)))

Action Chaining

Actions in an activity are executed in order. The action list in an activity definition specifies each action with its arguments:

:actions ((html-with-enumeration stream :itemize)
          (html-enumerating-item stream)
          (html-trace stream)
          (generate-inferiors))

Encapsulating actions nest around subsequent actions via call-next-action, creating a structured output tree.

14.5 Walking Programmatically

The walk generic function initiates a web walk. It accepts a URL (string or url:http-url object) and an activity (object or name string).

;; Walk using a named activity
(walk "http://www.example.com/" "trace-walk")

;; Walk with a dynamic activity
(w4:with-activity ("crawl"
                   (:report-stream '*standard-output*)
                   :constraints '((depth 2)
                                  (no-cycles)
                                  (header-robots-allowed))
                   :actions '((trace)
                              (trace-headers)
                              (generate-inferiors)))
  (walk "http://www.example.com/" activity))

Convenience Function

The trace-web function provides a convenient interface for quick exploration:

(w4::trace-web (url:intern-url "http://www.example.com/")
               3   ; depth
               :hosts '("www.example.com")
               :content-type '(:text :html)
               :respect-robot-protocol-p t)

Control Variables

w4:*debug-walker*
When true, enter the debugger on errors instead of continuing.
w4:*trace-walker*
When true, trace walk activity to w4:*report-stream*.
w4:*user-agent*
The User-Agent string sent with requests. Default: "W4 Constraint-Guided Walker".
w4:*standard-get-robot-headers*
Default headers for GET requests during walking.
w4:*standard-head-robot-headers*
Default headers for HEAD requests during walking.

Proxy Support

Set w4:local-proxy to route all walker HTTP requests through a proxy server. This is useful for accessing sites behind firewalls or for using the CL-HTTP caching proxy.