↓Skip to main content

Crawling the Web with Racket

·6 mins

At our company demo session last week, one of my (non-technical) colleagues showed off a web crawler he’d written in Python with help from ChatGPT. He needed to collect some e-commerce videos and metadata from online fashion retailers for some research he was doing. While I was impressed that he’d managed to put together a working solution, I was surprised that it had taken 218 lines of Python code and that ChatGPT had him implementing a crawler from scratch when they could have used a package like Scrapy.

I joked that I expected it to be about 20 lines of code, but this got me thinking: just how much code is needed to implement a web crawler? I’ve been playing around with Racket recently so thought I’d try implementing a basic web crawler in Racket. To keep things achievable, I would not handle dynamic content (no attempt to evaluate JavaScript) and it would be single-threaded. It wouldn’t obey robots.txt but to be kind to sites being crawled I included support for a delay between requests and a limit on the total number of pages retrieved from a site. The building blocks of a web crawler are:

  • An HTTP client;
  • A permissive HTML parser;
  • Sets for tracking unexplored URLs and those already visited.

So my toolbox consisted of the http-easy client, html-parsing and xml/path to navigate the HTML, and the core racket/set library to keep track of the work. With these in hand, it’s quite straightforward to retrieve a web page and find all the links:

(require (prefix-in http: net/http-easy)
         html-parsing
         xml/path)

;; Grab the content
(define res (http:get "https://1729.org.uk"))

;; Parse the body to an x-expression
(define xpr (html->xexp (bytes->string/utf-8 (http:response-body res))))

;; Use xml/path function to get a list of links
(se-path*/list '(a @ href) xpr)
'("#"
  "/"
  "/about/"
  "/posts/"
  "/categories/"
  "/tags/"
  "mailto:ray@1729.org.uk"
  "https://github.com/ray1729/"
  "https://facebook.com/ray1729"
  "https://social.linux.pizza/@ray1729"
  "https://www.linkedin.com/in/raymilleruk/"
  "https://stackoverflow.com/users/893721/ray1729"
  "https://creativecommons.org/licenses/by-nc-sa/4.0/")

We can see that we need to handle relative URLs, which we can do with the combine-url/relative function:

(require net/url)

(url->string (combine-url/relative (string->url "https://1729.org.uk") "/about/"))
"https://1729.org.uk/about/"

We also want to remove URL fragments (the bit of the URL after the #) and drop non-HTTP URLs from the list. I wrote a couple of helper functions for the URL extraction:

(define (url-without-fragment u)
  (struct-copy url u (fragment #f)))

(define (extract-links base-url xpr)
  (list->set (map url->string
                  (filter (lambda (u) (or (string=? (url-scheme u) "http") (string=? (url-scheme u) "https")))
                          (map (lambda (u) (url-without-fragment (combine-url/relative base-url u)))
                               (se-path*/list '(a @ href) xpr))))))

To wrap up our processing of a single URL, we need to check the status code and content type of the response and call a user-supplied handler function, returning the set of links from that page:

(define (process url handler)
  (match (http:get url)
    ((http:response #:status-code 200 #:headers ((content-type (regexp #"text/html"))) #:body body)
     (let ((x (html->xexp (bytes->string/utf-8 body))))
       (handler url x)
       (extract-links (string->url url) x)))
    (_ (set))))

This function silently ignores HTTP errors and any content that’s not HTML. Applying it to my home page with a no-op handler:

(process "https://1729.org.uk" (lambda (u x) #f))
(set
 "https://1729.org.uk/categories/"
 "https://1729.org.uk/tags/"
 "https://creativecommons.org/licenses/by-nc-sa/4.0/"
 "https://stackoverflow.com/users/893721/ray1729"
 "https://social.linux.pizza/@ray1729"
 "https://1729.org.uk/"
 "https://www.linkedin.com/in/raymilleruk/"
 "https://1729.org.uk/about/"
 "https://1729.org.uk/posts/"
 "https://1729.org.uk"
 "https://github.com/ray1729/"
 "https://facebook.com/ray1729")

With this function in hand, the main body of the crawler that keeps track of unvisited URLs (the frontier) and the visited set can be implemented:

(define (crawl url handler #:limit (limit #f) #:delay (delay (lambda () #f)) #:wanted? (wanted? (lambda (url) #t)))
  (let crawl ((frontier (set url)) (visited (set)))
    (unless (or (set-empty? frontier) (and limit (>= (set-count visited) limit)))
      (if (not (wanted? (set-first frontier)))
          (crawl (set-rest frontier) visited)
          (let ((links (process (set-first frontier) handler))
                (visited (set-add visited (set-first frontier))))
            (delay)
            (crawl (set-union (set-rest frontier) (set-subtract links visited)) visited))))))

This function accepts optional keyword arguments #:limit to limit the number of pages visited, #:delay to pass a function to sleep for a short time between requests, and #:wanted? to filter out “uninteresting” URLs. The most common use of the #:wanted? function is to limit the crawler to a single site, and I provided a utility function for this:

(define (host=? host)
  (lambda (u) (string=? host (url-host (string->url u)))))

The code is available on GitHub and runs to a total of 33 lines.

Using this library, we can implement the video downloader for my colleague:

#lang racket

(require racket-utils/crawler
         xml/path
         net/url
         json
         (prefix-in http: net/http-easy))

;; Utility function to construct a local path from a URL, with the first component
;; being the hostname, and remaining components the path from the URL.
(define (path-for base-dir url)
  (let ((url (string->url url)))
    (apply build-path base-dir (url-host url) (map path/param-path (url-path url)))))

;; If multiple videos are found at the same URL, increment an index so we save them with a
;; unique name.
(define (next-index dirname)
  (let next-index ((i 1))
    (if (file-exists? (build-path dirname (format "metadata_~a.json" i)))
        (next-index (add1 i))
        i)))

;; Function to download the videos and save to disk along with the metadata we crawled.
(define (save-videos videos dirname)
  (set-for-each videos (lambda (video)
                         (let* ((dirname (path-for dirname (hash-ref video 'url)))
                                (ix (next-index dirname)))
                           (make-directory* dirname)
                           (call-with-output-file (build-path dirname (format "metadata_~a.json" ix))
                             (lambda (out) (write-json video out #:indent 2)))
                           (call-with-output-file (build-path dirname (format "video_~a.mp4" ix))
                             (lambda (out)
                               (let ((in (http:response-output (http:get (hash-ref video 'src) #:stream? #t))))
                                 (copy-port in out)
                                 (close-input-port in))))))))

;; Main entrypoint
(define (crawl-videos url dest-dir limit delay-secs)

  ;; The set of video links and their metadata found by the crawler
  (define videos (mutable-set))

  ;; The handler we pass to the crawler. Its job is to save the page URL and the `src` and `alt` tags from
  ;; any MP4 videos found on that page.
  (define (collect-videos url page-content)
    (for-each (lambda (v)
                (let ((src (se-path* '(@ src) v))
                      (alt (se-path* '(@ alt) v)))
                  (when (string-suffix? src ".mp4")
                    (set-add! videos (hash 'url url 'src src 'alt alt)))))
              (se-path*/list '(video) page-content)))

  ;; The name of the host we're crawling, used below in the `host=?` function.
  (define host (url-host (string->url url)))

  ;; Call the crawler with our handler and an optional delay function.
  (if delay-secs
      (crawl url collect-videos #:limit limit #:wanted? (host=? host) #:delay (delay-upto delay-secs))
      (crawl url collect-videos #:limit limit #:wanted? (host=? host)))

  ;; Save the videos to `dest-dir`.
  (save-videos videos dest-dir))

That’s a further 42 lines of code, giving us a total of 75 loc - about 1/3 of the length of ChatGPT’s Python solution. I was very impressed with the ease of implementing this in Racket, even for a novice to the language. The libraries I needed were readily available and it’s extremely powerful to be able to experiment in a REPL during development.