# Work from a saved copy: fetch a page once, check it often

Save one fetched page to a file, then point the lesson 2 check at that file so you can edit and rerun it as often as you like with no new request.

Canonical: https://spider.cloud/learn/course/work-from-a-saved-copy/

You need not ask a site for a page again each time you change the code that reads it: fetch it once, write the answer to a file, and point your check at the file. Two files come out of it: `page1.md`, a 4274 byte copy of one practice page, and `check_copy.py`, the lesson 2 check with one more branch that reads that file and sends nothing.

Lesson 4 ended on a question. To compare two pauses, it asked the practice site for the same three pages twice. That was the point of the exercise, but most repeat fetches are not. When you are still getting a word check or a parser right, you run it again after every edit, and the page does not change between runs. Each of those runs can read the same file.

## One request per run, until now

[Lesson 2](/learn/course/write-the-script/) gave you `check_page.py`, which takes an address and a word, fetches the page, and exits 0 when the page answered 200 and holds the word, 1 when there is no page to check, and 2 when the word is missing. Every run sent one request. [Lesson 4](/learn/course/pace-your-requests/) measured what a request costs in time at a polite rate, and the site pays its share of that cost on every run too.

This lesson splits the job in two. One script fetches and saves. The other checks, and it can check either a live address or a saved file.

## Save the page once

`save_copy.py` is lesson 2's request with the word check taken out. In its place are the last three lines of `main()`: it encodes the `content` field, writes those bytes to the file you name, and prints how many there were. It writes nothing when the status is not 200, so a 404 page never ends up on disk posing as the real one.

It finds your API key in the `SPIDER_API_KEY` environment variable, and every import comes from the standard library. This is the file as it ran on 2026-11-20.

```python
"""Fetch one page through the Spider API once and keep its content in a file.

    python3 save_copy.py URL FILE

Exit 0: the page answered 200 and FILE holds its content.
Exit 1: the key is missing or the status is not 200, and no file was written.
"""
import json
import os
import sys
import urllib.request
from pathlib import Path

API = "https://api.spider.cloud/scrape"


def main() -> int:
    if len(sys.argv) != 3:
        print("usage: python3 save_copy.py URL FILE")
        return 1
    url, out = sys.argv[1], Path(sys.argv[2])
    key = os.environ.get("SPIDER_API_KEY")
    if not key:
        print("set SPIDER_API_KEY first, as in lesson 1")
        return 1

    body = json.dumps({"url": url, "request": "http", "return_format": "markdown"}).encode()
    req = urllib.request.Request(API, data=body, headers={
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
    })
    with urllib.request.urlopen(req, timeout=60) as resp:
        page = json.load(resp)
    if isinstance(page, list):
        page = page[0]

    status = page.get("status")
    print(f"url: {page.get('url')}")
    print(f"status: {status}")
    if status != 200:
        print("nothing saved")
        return 1
    data = (page.get("content") or "").encode()
    out.write_bytes(data)
    print(f"saved: {len(data)} bytes to {out}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
```

Running the same name twice replaces the old copy. The pathlib documentation says of `write_bytes()` that "An existing file of the same name is overwritten." Use a new name when you want to keep the earlier copy next to the new one.

The script above is printed as it ran, and its request body carries no `user_agent`. Before you run it, give it the name from lesson 2: replace the `body = ...` line with this, using your own bot name and address.

```python
    body = json.dumps({
        "url": url,
        "request": "http",
        "return_format": "markdown",
        "user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)",
    }).encode()
```

Then fetch the page and save it.

```bash
python3 save_copy.py https://quotes.toscrape.com/page/1/ page1.md
```

This is what it printed on 2026-11-20, with Python 3.14.7, and it exited 0.

```text
url: https://quotes.toscrape.com/page/1/
status: 200
saved: 4274 bytes to page1.md
```

That was the only request the recorded runs in this lesson sent to the practice site. Both checks below read `page1.md`.

## Teach the check to read a file

`check_copy.py` keeps lesson 2's three exit codes and its word check. The request moved into a `fetch()` function that returns the page text, or `None` when there is no page to check. The new part is the branch in `main()`: when the first argument does not start with `http://` or `https://`, the script treats it as a path, exits 1 if no file is there, and reads the text with `read_text()`. Then it encodes that text again, prints the length of the result in bytes, and says that no request went out. The word check after that is the same line it was in lesson 2, so a file and a live page are judged the same way.

```python
"""The lesson 2 check, now able to read a saved copy instead of fetching.

    python3 check_copy.py SOURCE WORD

SOURCE is an address to fetch through the Spider API, or a file save_copy.py wrote.
A file costs no request, so you can check it as often as you like.

Exit 0: the page answered 200, or the file exists, and it holds WORD.
Exit 1: no page to check: the key is missing, the status is not 200, or there is no file.
Exit 2: the page or the file has no WORD in it.
"""
import json
import os
import sys
import urllib.request
from pathlib import Path

API = "https://api.spider.cloud/scrape"


def fetch(url: str) -> str | None:
    key = os.environ.get("SPIDER_API_KEY")
    if not key:
        print("set SPIDER_API_KEY first, as in lesson 1")
        return None
    body = json.dumps({"url": url, "request": "http", "return_format": "markdown"}).encode()
    req = urllib.request.Request(API, data=body, headers={
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
    })
    with urllib.request.urlopen(req, timeout=60) as resp:
        page = json.load(resp)
    if isinstance(page, list):
        page = page[0]
    print(f"url: {page.get('url')}")
    print(f"status: {page.get('status')}")
    if page.get("status") != 200:
        print("no page to check")
        return None
    return page.get("content") or ""


def main() -> int:
    if len(sys.argv) != 3:
        print("usage: python3 check_copy.py SOURCE WORD")
        return 1
    source, word = sys.argv[1], sys.argv[2]
    if source.startswith(("http://", "https://")):
        text = fetch(source)
    else:
        path = Path(source)
        if not path.is_file():
            print(f"no copy at {path}")
            return 1
        text = path.read_text()
        print(f"file: {path}, {len(text.encode())} bytes, no request sent")
    if text is None:
        return 1
    if word not in text:
        print(f"missing: {word!r}")
        return 2
    print(f"found: {word!r}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
```

The file branch never looks for the key. The pathlib documentation describes `read_text()` as one that will "Return the decoded contents of the pointed-to file as a string", so the number the check prints is a count of that string encoded again, not the size the disk reports. With no `encoding` argument, `read_text()` decodes with your system's default, and it turns Windows line endings into plain newlines on the way in, so on some machines the two counts differ. In your copy, change the read to this, which matches the UTF-8 that `save_copy.py` wrote:

```python
        text = path.read_text(encoding="utf-8")
```

If the counts still differ, ask the disk. `wc -c page1.md` prints the file's real size, and it should match the number `save_copy.py` printed, since `write_bytes()` writes exactly those bytes.

`fetch()` sends the same body `save_copy.py` did, so make the same `user_agent` change there before you give the check a live address.

## Check the copy, then check it again

Both runs below read that same file, on 2026-11-20. The first looks for a name the page holds.

```bash
python3 check_copy.py page1.md Einstein
```

```text
file: page1.md, 4274 bytes, no request sent
found: 'Einstein'
```

It exited 0, and the count it printed, 4274, is the number the save printed.

The second changes only the word, to one the quotes page does not hold.

```bash
python3 check_copy.py page1.md Pricing
```

```text
file: page1.md, 4274 bytes, no request sent
missing: 'Pricing'
```

That run exited 2, the code lesson 2 set aside for a missing word. In both runs the `file:` line ends with `no request sent`, and that holds however many times you rerun them: the practice site has still had one request from these runs, the one that made the file.

## How old the copy is

A saved copy answers one question: what did the page hold when you fetched it? It cannot tell you what the page holds now. RFC 9111, the HTTP caching standard, states the trade a cache makes: "The goal of HTTP caching is significantly improving performance by reusing a prior response message to satisfy a current request." Your file is a small cache of your own, with the same limit. A pass on `page1.md` is a pass on the page as it was on the day you saved it.

So keep the two kinds of run apart. While you edit the check, point it at the file. When you need today's page, give it the address once, or run `save_copy.py` again under a new name and compare the two byte counts. Fetching only when you need something new, and doing the rest of the work on what you already have, is a habit any [web scraping](/web-scraping/) job gains from as it grows.

## Try it yourself

Save the second quotes page, which is one new request, then clear the key from your shell and check the copy twice. Page 2 holds a quote by J.K. Rowling and, like page 1, has no pricing on it. `echo $?` prints the exit code of the command just before it.

```bash
python3 save_copy.py https://quotes.toscrape.com/page/2/ page2.md
unset SPIDER_API_KEY
python3 check_copy.py page2.md Rowling
echo $?
python3 check_copy.py page2.md Pricing
echo $?
```

The first check should end with `found: 'Rowling'` and print 0. The second should end with `missing: 'Pricing'` and print 2. You are done when you get those two results, each `file:` line ends with `no request sent` and shows the count the save printed (or `wc -c page2.md` does), and neither check ran with a key in the shell. Then try your own words and rerun as often as you like.

## Do this, avoid this

### Do this

- Save the page once, under a name that says which page it is.
- Point the check at the file while you edit it, and at the address only when you need today's page.
- Write down the day you saved each copy.
- Keep saved copies for your own checks. Read the site's terms before you share one, since the text is still under its author's copyright.

### Avoid this

- Fetching the live page again each time you change one word in the check.
- Trusting a pass on an old copy to mean the live page still holds the word.
- Saving a copy when the status was not 200.
- Overwriting a copy you meant to compare with a newer one.

## Next

So far the check has asked whether one word is on one page. The next lesson asks which other addresses that page links to, and `page1.md` is a copy you can ask it of without fetching anything new.

## Sources

1. [Python documentation, pathlib module, Path.read_text and Path.write_bytes](https://docs.python.org/3/library/pathlib.html) Read November 21, 2026
2. [RFC 9111, HTTP Caching, IETF, June 2022](https://www.rfc-editor.org/rfc/rfc9111.html) Read November 21, 2026
