Saving websites for offline reading with ScrapePy
ScrapePy keeps a working offline copy of a website, and a second run only fetches the pages that have changed.
Saved literally, a news address such as /news/12345/1/slug would become three nested folders holding one file. ScrapePy saves it as news/slug-12345-1.html. Rules like that one turn a live website into a copy that works with no connection, as HTML and as Markdown, and a second run only fetches what has changed.
Look before crawling
Before it fetches any content, ScrapePy runs a short reconnaissance step. It reads robots.txt to find the sitemaps, reads the sitemaps and any RSS or Atom feeds to build a map of URLs and their dates, and parses the home page’s header, navigation and footer, including dropdown menus. It saves the site’s section structure to site_outline.json, and I have it start the crawl from the navigation instead of just the home page: on a large site the sections are found early, and with date filtering on, old articles can be skipped without being fetched.
One URL, one file
For a copy to work offline, every page and image has to be saved, every link has to point at the copy, and each URL needs one fixed place on disk. /about becomes about.html, / becomes index.html, and anything with an extension keeps it. News sites often have numeric IDs in their paths, and numeric segments next to the file name are folded into it, which is how the news address above ends up as one file.
URLs come from the site being copied and can’t be trusted. After mapping, the path is normalised and checked: if it would land outside the output folder, it falls back to a flat file name.
result = os.path.normpath(os.path.join(config.output_dir, clean))
output_dir_resolved = os.path.normpath(config.output_dir)
if not result.startswith(output_dir_resolved + os.sep) and result != output_dir_resolved:
safe_name = clean.replace("/", "_").replace("\\", "_")
result = os.path.join(config.output_dir, safe_name)
Rewriting the links
Once a page is saved, its links still point at the live site. The rewriter goes through every href and src, decides whether it’s internal, and points internal ones at the copy with a path relative to the current file.
Fragments, mailto:, tel:, javascript: and data: links are left alone. Root-relative paths and URLs starting with the site’s base URL are internal. Any other absolute URL is external. Anything else is a relative path, and so internal.
Internal links are then sorted by type. Stylesheets point into css/, scripts into js/, images into images/, and documents such as PDFs into media/. Pages point at their mapped HTML file. With --stay-in-path, a page outside the starting path points back to the live site instead of to a file that was never downloaded.
Only fetch what changed
Re-downloading a whole site to refresh it is slow and puts needless load on the server, so ScrapePy keeps a small cache file in each copy, with the ETag, Last-Modified value and a SHA-256 hash of every page.
On the next run it sends conditional request headers:
def get_page_headers(self, url_path: str) -> dict:
entry = self._data["pages"].get(url_path)
if not entry:
return {}
headers = {}
if entry.get("etag"):
headers["If-None-Match"] = entry["etag"]
if entry.get("last_modified"):
headers["If-Modified-Since"] = entry["last_modified"]
return headers
If the server answers 304 Not Modified, the page is skipped. The crawl still needs the links on that page, though, or it would never reach the pages behind it, so the cache stores each page’s links and replays them. Plenty of servers don’t send these headers at all. For those, ScrapePy fetches the page and compares its hash with the stored one, and skips the write if nothing changed.
A Markdown copy too
Alongside the HTML, ScrapePy writes a Markdown copy of the site, which is easier to search and diff. Each file starts with YAML frontmatter: title, URL, date, page type, word count and description. The image folders are copied across so the Markdown’s image links still work. Turning saved web pages into clean Markdown covers how each page’s article is found and its menus and adverts left out.
ScrapePy looks for the date in several places and ranks them by how much it trusts each one: a meta tag first, then JSON-LD, then a date in the URL, then a <time> element, and the HTTP headers last. The frontmatter records which source it used.
A copy of your own
Follow each site’s terms, respect its robots.txt and rate limits, and only keep what you have the right to keep. Three commands install it and copy a documentation site:
pip install .
scrapling install
scrapepy https://docs.example.com/guide/ --stay-in-path
The HTML copy goes into ScrapedSites/ and the Markdown into MarkdownSites/.
More on ScrapePy
Featured projects
-
Apple News API
Publish articles and live coverage to Apple News from PHP, with the whole Apple News Format built from objects.
-
GitHub Auditor
Health, access and activity reports for more GitHub and Bitbucket repositories than you can keep in your head.
-
PrintMD
Markdown in, and a designed PDF, Word or PowerPoint file out. Its PDF service runs on your own computer.
-
Where Should I Live
Which city would leave you best off? Cities ranked by take-home pay, living costs, visas and the way you live.
-
Solar Calendar
Thirteen months of exactly four weeks, with the year starting on the first Monday on or after the spring equinox.
More writing
-
Many sessions at once, and what still needs me
Fifteen coding-agent sessions across two Linux boxes, one session that watches the rest, what it may answer for me, what it never may, and why a yes it passes on gets checked against what I typed.
-
61 public repos of agent tooling, none installed, six ideas kept
One author, 61 public repositories of coding-agent tooling: what I checked before any of it got near my Linux boxes, why none of it was installed, and the six ideas I built my own way.
-
Rules a coding agent cannot talk its way round
The hook that reads every command a coding agent wants to run on my Linux boxes: what it refuses, the 27 proofs that its tests fail when a rule is taken out, and the four lines every report opens with.
-
Dozens of repos, one person
46 repositories and two Linux boxes with nobody else on them: the diary, the decision table, the rebuild guide and the job that keeps both sets of clones in step.