# Save a crawl to CSV: one row per page, with a header | Spider

Add a CSV writer to the lesson 7 crawl, write url, status and bytes for each page to quotes.csv, and read the first rows of a dated 20-row file.

Canonical: https://spider.cloud/learn/course/save-to-csv/

To save scraped data to CSV, give each page one row and each thing you measured one column, put the column names on the first line, and let a CSV library write the rows. In Python that library is the standard `csv` module, and the file you hand it should be opened with `newline=""`.

This lesson leaves you with `quotes.csv`, a file with a header row and then one row for each page your crawl returns. Each row holds the page's address, its status code and the size of its text in bytes. You also have `crawl_csv.py`, the script that writes it.

## Where crawl.py left off

[Lesson 7](/learn/course/crawl-a-site/) gave you `crawl.py`, which sends one crawl call with a limit of 20 and prints a status and an address per page. [Lesson 8](/learn/course/set-the-depth/) ran it at depth 1 and depth 2 and left you with three lists in a terminal, which you cannot sort or open later.

`crawl_csv.py` is a copy of `crawl.py` with the printing swapped for a file. Here is what changed. It imports `csv`. It takes a second argument, the file name, in place of the depth. It builds a sorted list of rows, each one an address, a status and a byte count. It opens the file, writes a header row and then all the rows. And it reads the file back and prints its first six lines, so you can see what landed on disk without opening anything else.

This clip reads the file row by row.

Save a crawl as a CSV file. 49 s, no sound. The words are on screen, and the captions button shows them at your own text size.

Read the transcript

Save a crawl as a CSV file. A crawl of a practice site, written as one row for each page.

The file starts with a header row, then one row for each page. saved: 20 rows to quotes.csv. url,status,bytes. https\://quotes.toscrape.com/,200,4274. https\://quotes.toscrape.com/login,200,128. https\://quotes.toscrape.com/page/2/,200,6460. 3: columns, named once. 3: of the rows, shown here.

Each row holds the address, the status and the size of the text. url: https\://quotes.toscrape.com/login. status: 200. bytes: 128. 3: values, in the header's order.

20 rows and 1 header make 21 records in the file. 1 header row. 20 data rows, one for each page. 21: records in quotes.csv. 0: exit code.

Exit 0 covers every row, also the rows not printed. What the exit code says: python3 crawl_csv.py. exit 0: Every row has status 200. exit 1: At least one row does not. This run: exit 0.

Read the full page. The page is at spider.cloud/learn/course/save-to-csv.

## Why newline matters

The line in the script that is easiest to get wrong is the `open()` call. The Python documentation says a file for the csv writer should be opened with that argument, and its footnote gives the reason: "If newline=" is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n line endings on write an extra \r will be added." The same note goes on, "It should always be safe to specify newline=", since the csv module does its own … newline handling."

That fits what the format itself asks for. RFC 4180, the IETF memo that describes CSV, says "Each record is located on a separate line, delimited by a line break (CRLF)." The csv writer ends each row with that line break on its own. Leave out `newline=""` on a system that ends lines with `\r\n`, such as Windows, and the file translates that break a second time. That is the extra `\r` the footnote warns about.

The memo also covers the first row. It calls the header optional and says "This header will contain names corresponding to the fields in the file". The script writes `url,status,bytes`, so the three columns are named before any data row. A program that reads the file later, yours or a spreadsheet's, needs no guessing.

## The whole of crawl_csv.py

As before, the key comes from `SPIDER_API_KEY` in your environment and never sits in the file. This copy is unchanged from its one run on 2026-11-20, under Python 3.14.7.

```python
"""Crawl a site through the Spider API, at most 20 pages, and save one CSV row per page.

    python3 crawl_csv.py URL FILE

Each row holds the page address, its status and the size of its text in bytes.
Exit 0: every page answered 200 and the file is written.
Exit 1: the key is missing, nothing came back, or a page answered something else.
"""
import csv
import json
import os
import sys
import urllib.request

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


def main() -> int:
    if len(sys.argv) != 3:
        print("usage: python3 crawl_csv.py URL FILE")
        return 1
    url, out = sys.argv[1], 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

    params = {"url": url, "limit": 20, "request": "http", "return_format": "markdown"}
    req = urllib.request.Request(API, data=json.dumps(params).encode(), headers={
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
    })
    with urllib.request.urlopen(req, timeout=300) as resp:
        pages = json.load(resp)
    if isinstance(pages, dict):
        pages = [pages]
    if not pages:
        print("nothing came back")
        return 1

    rows = sorted(((p.get("url") or "", p.get("status"), len((p.get("content") or "").encode()))
                   for p in pages))
    # newline="" lets the csv module write its own line endings, as its docs ask.
    with open(out, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["url", "status", "bytes"])
        writer.writerows(rows)

    print(f"saved: {len(rows)} rows to {out}")
    with open(out, newline="", encoding="utf-8") as f:
        for line in f.read().splitlines()[:6]:
            print(f"  | {line}")
    return 0 if all(status == 200 for _, status, _ in rows) else 1


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

That run left out a `user_agent` and a `delay`, and yours should not. Make the `params` line read as below, with your own bot name and contact in place of the example ones. The `delay` of 1000 asks for one second between requests. The recorded run sent no delay, so its time says nothing about how long yours will take.

```python
    params = {"url": url, "limit": 20, "request": "http", "return_format": "markdown",
              "user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)", "delay": 1000}
```

## Write the file

```bash
python3 crawl_csv.py https://quotes.toscrape.com/ quotes.csv
```

Run on 2026-11-20, the command took 3.3 seconds, exited 0 and left this on screen.

```text
saved: 20 rows to quotes.csv
  | url,status,bytes
  | http://quotes.toscrape.com/author/Eleanor-Roosevelt/,200,1527
  | http://quotes.toscrape.com/author/J-K-Rowling/,200,4010
  | https://quotes.toscrape.com/,200,4274
  | https://quotes.toscrape.com/login,200,128
  | https://quotes.toscrape.com/page/2/,200,6460
```

## Read the rows

The count comes first. The script counts rows before the header goes in, so the 20 rows of the 2026-11-20 run make 21 CSV records in the file, header included. The API reference describes `limit` as the most pages to crawl per site, so 20 is a ceiling. That run returned 20 pages, and the file holds one row per page. Your own run may return fewer.

Exit 0 says more than the five rows shown. The script returns 0 only when every row in the list has status 200, so the 15 rows the printout leaves out answered 200 as well.

The rows are sorted by address, and `http://` sorts before `https://`, which is why the two author pages sit above the front page. Their addresses came back starting with `http://` and ending in a slash, the same pattern the author pages in lesson 7 showed. The file records each address as the crawl returned it, and anything you build on the file should keep it that way.

The bytes column is the length of each page's markdown text, as the script measures it. `/login` holds 128 bytes of text and `/page/2/` holds 6460. Lesson 8's lists had no column like this to compare. In a spreadsheet you can now sort on it.

None of the six lines shown needed quoting, because no field in them holds a comma, a quote mark or a line break. Add a column of page titles and some fields will. The csv writer quotes those for you, following the rule RFC 4180 gives as "Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes." Joining strings with commas by hand gets this wrong the first time a title holds one.

This is your first CSV of crawl results from a [web scraping](/web-scraping/) job: a list you can sort and open again, where lesson 8's lists only scrolled past in a terminal.

## Try it yourself

Change `"limit": 20` to `"limit": 5` in your copy, keep the `user_agent` and `delay` you added, and write to a new file so `quotes.csv` stays as it is. Then count the records with the csv module. It reads the file the way it was written, so a quoted field that spans two physical lines still counts as one record:

```bash
python3 crawl_csv.py https://quotes.toscrape.com/ quotes5.csv
echo $?
python3 -c 'import csv; print(sum(1 for _ in csv.reader(open("quotes5.csv", newline="", encoding="utf-8"))))'
```

You are done when the first line reads `saved: 5 rows to quotes5.csv` or names fewer than 5, `echo $?` prints 0, and the last command prints one more than that row count, because the header is a record too.

Before you point the script at a site you do not own, read its robots.txt as in [lesson 3](/learn/course/read-robots-txt/).

## Do this, avoid this

### Do this

- Open every CSV file with newline set to an empty string and encoding utf-8, when you write it and when you read it back.
- Write the header row first, with one name per column.
- Write rows through csv.writer, so a comma or quote mark inside a field gets quoted for you.
- Store each address exactly as the crawl returned it.

### Avoid this

- Joining fields with commas by hand.
- Counting the header as a page when you check the row count.
- Adding a column of page text before you know whether that text is under copyright.
- Writing names, emails or other personal data into the file when your question does not need them.

## Next

The script opens `quotes.csv` with `"w"`, so the next run on the same name replaces the file and the 2026-11-20 rows are gone. The next lesson asks how to keep every run's file, so you can set one day's crawl beside another's.

## Sources

1. [Python documentation, csv: CSV File Reading and Writing](https://docs.python.org/3/library/csv.html) Read November 21, 2026
2. [RFC 4180, Common Format and MIME Type for Comma-Separated Values (CSV) Files, IETF, October 2005](https://www.rfc-editor.org/rfc/rfc4180.html) Read November 21, 2026
