Web scraping
I often write software to automatically collect and use data from the web and other sources. As a practical matter, much of the data that many people use for machine learning comes from either the web or from internal data sources. This section provides some guidance and examples for getting text data from the web.
Before we start a technical discussion about web scraping I want to point out that much of the information on the web is copyright, so first you should read the terms of service for web sites to insure that your use of “scraped” or “spidered” data conforms with the wishes of the persons or organizations who own the content and pay to run scraped web sites.
We start with low-level Racket code examples in the GitHub repository for this book in the directory Racket-AI-book/source-code/misc_code. We will then implement a standalone library in the directory Racket-AI-book/source-code/webscrape.
Getting started web scraping
All of the examples in the section can be found in the Racket code snippet files in the directory Racket-AI-book/source-code/misc_code.
I have edited the output for brevity in the following REPL output:
1 $ racket
2 Welcome to Racket v8.10 [cs].
3 > (require net/http-easy)
4 > (require html-parsing)
5 > (require net/url xml xml/path)
6 > (require racket/pretty)
7 > (define res-stream
8 (get "https://markwatson.com" #:stream? #t))
9 > res-stream
10 #<response>
11 > (define lst
12 (html->xexp (response-output res-stream)))
13 > lst
14 '(*TOP*
15 (*DECL* DOCTYPE html)
16 "\n"
17 (html
18 (@ (lang "en-us"))
19 "\n"
20 " "
21 (head
22 (title
23 "Mark Watson: AI Practitioner and Author of 20+ AI Books | Mark Watson")
24 ...
Different element types are html, head, p, h1, h2, etc. If you are familiar with XPATH operations for XML data, then the function se-path*/list will make more sense to you. The function se-path*/list takes a list of element types from a list and recursively searches an input s-expression for lists starting with one of the target element types. In the following example we extract all elements of type p:
1 > (se-path*/list '(p) lst) ;; get text from all p elements
2 '("My customer list includes: Google, Capital One, Babylist, Olive AI, CompassLabs, Mind AI, Disney, SAIC, Americast, PacBell, CastTV, Lutris Technology, Arctan Group, Sitescout.com, Embed.ly, and Webmind Corporation."
3 "I have worked in the fields of general\n"
4 " artificial intelligence, machine learning, semantic web and linked data, and\n"
5 " natural language processing since 1982."
6 "My eBooks are available to read for FREE or you can purchase them at "
7 (a (@ (href "https://leanpub.com/u/markwatson")) "leanpub")
8 ...
1 > (define lst-p (se-path*/list '(p) lst))
2 > (filter (lambda (s) (string? s)) lst-p) ;; keep only text strings
3 '("My customer list includes: Google, Capital One, Babylist, Olive AI, CompassLabs, Mind AI, Disney, SAIC, Americast, PacBell, CastTV, Lutris Technology, Arctan Group, Sitescout.com, Embed.ly, and Webmind Corporation."
The strings still contain the line breaks and runs of spaces from the HTML source, so we join them and clean up the white space:
1 > (string-normalize-spaces
2 (string-join
3 (filter (lambda (s) (string? s)) lst-p)
4 "\n"))
5 "My customer list includes: Google, Capital One, Babylist, Olive AI, CompassLabs, Mind AI, Disney, SAIC, Americast, PacBell, CastTV, Lutris Technology, Arctan Group, Sitescout.com, Embed.ly, and Webmind Corporation. I have worked in the fields of general artificial intelligence, machine learning, semantic web and linked data, and natural language processing since 1982.
6 ...
7 "
Extracting the anchor links takes one call:
1 > (se-path*/list '(href) lst) ;; get all links from HTML as a list
2 '("/index.css"
3 "https://mark-watson.blogspot.com"
4 "#fun"
5 "#books"
6 "#opensource"
7 "https://markwatson.com/privacy.html"
8 "https://leanpub.com/u/markwatson"
9 "/nda.txt"
10 "https://mastodon.social/@mark_watson"
11 "https://twitter.com/mark_l_watson"
12 "https://github.com/mark-watson"
13 "https://www.linkedin.com/in/marklwatson/"
14 "https://markwatson.com/index.rdf"
15 "https://www.wikidata.org/wiki/Q18670263"
16 ...
17 )
Implementation of a Racket web scraping library
The web scraping library listed below can be found in the directory Racket-AI-book/source-code/webscrape. The following listing of webscrape.rkt should look familiar after reading the code snippets in the last section.
The library has two layers. The functions whose names start with xexp-> work on a page that has already been parsed, so they can be used on HTML from any source and tested without a network connection. The functions whose names start with web-uri-> fetch a page first and then call the matching xexp-> function.
- web-uri->xexp fetches a URI with the get function from net/http-easy and parses the HTML into an S-expression (an xexp) with html->xexp from the html-parsing library. It uses a connection timeout and a request timeout, and it raises an error for any HTTP status other than a 2xx success code, so a “404 not found” page is never mistaken for real content.
- html-string->xexp parses HTML that you already have in a string.
- xexp->text uses se-path*/list from the xml/path library to collect the contents of all paragraph (p) elements, keeps only the strings (dropping nested tags), joins them, and cleans up white space with string-normalize-spaces.
- xexp->links collects all href attribute values. Called with just a page it returns only absolute links, those starting with “http”. Called with the page’s own URI as a second argument it also resolves relative links such as “/about.html” into absolute URLs using combine-url/relative, and skips links that are not web pages (in-page anchors, mailto:, and javascript: links).
- xexp->html-headers returns three lists with the text of the h1, h2, and h3 headers.
- web-uri->text, web-uri->links, and web-uri->html-headers fetch a page and apply the function above. web-uri->links takes the keyword argument #:resolve-relative? #t to include relative links.
1 #lang racket
2
3 ;;; webscrape.rkt — Web scraping utilities for Racket
4 ;;; Copyright (C) 2022-2026 Mark Watson
5 ;;; Apache 2 License
6 ;;;
7 ;;; The library is split into two layers:
8 ;;; - pure functions that work on an already-parsed page (an xexp),
9 ;;; which can be tested without a network connection, and
10 ;;; - web-uri->... convenience functions that fetch a page first.
11
12 (require net/http-easy)
13 (require html-parsing)
14 (require net/url xml xml/path)
15
16 (provide web-uri->xexp
17 web-uri->text
18 web-uri->links
19 web-uri->html-headers
20 html-string->xexp
21 xexp->text
22 xexp->links
23 xexp->html-headers)
24
25 ; Parse a string of HTML into an XExp structure
26 (define (html-string->xexp html)
27 (html->xexp html))
28
29 ; Fetch a web page and return its HTML as an XExp structure.
30 ; A-URI is a URL string or bytes. Raises exn:fail:network on connection
31 ; problems and exn:fail on any HTTP status other than 2xx.
32 (define (web-uri->xexp a-uri)
33 (define resp
34 (get a-uri
35 #:stream? #t
36 #:timeouts (make-timeout-config #:connect 10 #:request 30)))
37 (define status (response-status-code resp))
38 (cond
39 [(<= 200 status 299)
40 (define xexp (html->xexp (response-output resp)))
41 (response-close! resp)
42 xexp]
43 [else
44 (response-close! resp)
45 (error 'web-uri->xexp "HTTP status ~a fetching ~a" status a-uri)]))
46
47 ; Extract all paragraph text from a parsed page
48 (define (xexp->text a-xexp)
49 (define p-elements (se-path*/list '(p) a-xexp))
50 ; Keep only strings (text content) and normalize whitespace
51 (define text-strings
52 (for/list ([elem p-elements]
53 #:when (string? elem))
54 elem))
55 (string-normalize-spaces
56 (string-join text-strings "\n")))
57
58 ; Extract links from a parsed page.
59 ; With no BASE-URI only absolute links (starting with http) are returned.
60 ; With a BASE-URI string, relative links such as "/about.html" are
61 ; resolved against it and returned as absolute URLs too.
62 (define (xexp->links a-xexp [base-uri #f])
63 (define all-hrefs
64 (filter string? (se-path*/list '(href) a-xexp)))
65 (define (absolute? href) (string-prefix? href "http"))
66 (cond
67 [base-uri
68 (define base (string->url base-uri))
69 (for/list ([href all-hrefs]
70 #:unless (or (string-prefix? href "#")
71 (string-prefix? href "mailto:")
72 (string-prefix? href "javascript:")))
73 (if (absolute? href)
74 href
75 (url->string (combine-url/relative base href))))]
76 [else (filter absolute? all-hrefs)]))
77
78 ; Extract HTML headers (H1, H2, H3) from a parsed page.
79 ; Returns a list of lists: (list (h1-headers...) (h2-headers...) (h3-headers...))
80 (define (xexp->html-headers a-xexp)
81 (for/list ([tag '(h1 h2 h3)])
82 (for/list ([h (se-path*/list (list tag) a-xexp)]
83 #:when (string? h))
84 h)))
85
86 ; Fetch a page and extract all paragraph text
87 (define (web-uri->text a-uri)
88 (xexp->text (web-uri->xexp a-uri)))
89
90 ; Fetch a page and extract all external links (starting with http).
91 ; Pass #:resolve-relative? #t to also get relative links as absolute URLs.
92 (define (web-uri->links a-uri #:resolve-relative? [resolve-relative? #f])
93 (xexp->links (web-uri->xexp a-uri)
94 (and resolve-relative?
95 (if (bytes? a-uri) (bytes->string/utf-8 a-uri) a-uri))))
96
97 ; Fetch a page and extract H1, H2, and H3 headers
98 (define (web-uri->html-headers a-uri)
99 (xexp->html-headers (web-uri->xexp a-uri)))
100
101 (module+ main
102 ; (web-uri->xexp "https://knowledgebooks.com")
103 ; (web-uri->text "https://knowledgebooks.com")
104 ; (web-uri->links "https://knowledgebooks.com")
105 (void))
Here are a few examples in a Racket REPL (most output omitted for brevity):
1 > (web-uri->xexp "https://knowledgebooks.com")
2 '(*TOP*
3 (*DECL* DOCTYPE html)
4 "\n"
5 (html
6 "\n"
7 "\n"
8 (head
9 "\n"
10 " "
11 (title "KnowledgeBooks.com - research on the Knowledge Management, and the Semantic Web ")
12 "\n"
13 ...
14
15 > (web-uri->text "https://knowledgebooks.com")
16 "With the experience of working on Machine Learning and Knowledge Graph applications
17 ...
18
19 > (web-uri->links "https://knowledgebooks.com")
20 '("http://markwatson.com"
21 "https://oceanprotocol.com/"
22 "https://commoncrawl.org/"
23 "http://markwatson.com/consulting/"
24 "http://kbsportal.com")
25
26 > (web-uri->html-headers "https://markwatson.com")
27 '((...) (... ...) ...) ; returns list of H1, H2, H3 header text lists
The functions that work on an already parsed page need no network, which makes them easy to experiment with:
1 > (define page
2 (html-string->xexp
3 "<h1>Title</h1><p>Some text.</p><a href=\"/about.html\">About</a>"))
4 > (xexp->text page)
5 "Some text."
6 > (xexp->links page)
7 '()
8 > (xexp->links page "https://example.com/blog/")
9 '("https://example.com/about.html")
10 > (xexp->html-headers page)
11 '(("Title") () ())
The file tests.rkt in the same directory tests the library this way, against a fixed HTML string. Run it with raco test tests.rkt.
The following diagram shows the high-level architecture of the web scraping library developed in this chapter:
If you want to install this library on your laptop using linking (requiring the library access a link to the source code in the directory Racket-AI-book/source-code/webscrape) run the following in the library source directory Racket-AI-book/source-code/webscrape:
1 raco pkg install --scope user
Being a good citizen
In addition to respecting copyright and terms of service, please keep two things in mind when you fetch more than a page or two from a site. First, most sites publish a robots.txt file (for example https://example.com/robots.txt) that says which paths automated clients should stay away from, and you should honor it. Second, pause between requests, for example with (sleep 1), so that your program does not put a noticeable load on someone else’s server.
The library in this chapter only sees the HTML that a server sends. Many modern pages build their content with JavaScript after the page loads, and for those pages web-uri->text returns little or nothing. The next chapter handles that case by driving a headless browser.
Optional practice problems
- Extract full page text: The
xexp->textfunction only retrieves text nested directly within<p>tags. Extend it to also extract text from headers (<h1>to<h6>), list items (<li>), and text inside nested tags such as links within a paragraph, to get a more complete textual representation of the page. - Check robots.txt: Write a function
allowed-by-robots?that fetches a site’srobots.txt, finds theDisallowlines that apply to all user agents, and returns#fwhen a given URI’s path starts with one of them. - A polite crawler: Using
web-uri->linkswith#:resolve-relative? #t, write a function that starts at one URI and visits pages on the same host up to a maximum count, sleeping one second between requests and usingwith-handlersso that one failed page does not stop the crawl.