Scraping Web Pages from the Command Line with shot-scraper

Terminal window running shot-scraper against books.toscrape.com, printing book titles and prices as JSON, then committing the result with git
A whole scraper in one command, with Git as the history.

I spent a good part of last weekend writing scrapers, and for once I did not write a single line of Python to do it. The tool that made that possible is shot-scraper by Simon Willison. It started life as a screenshot tool, and a few days ago he added a javascript command that turns it into a scraper. You give it a URL and a JavaScript expression. It opens the page in a real headless Chromium, runs your expression, and prints whatever comes back as JSON.

That sounds small. It changed how I write scrapers, so this post is my notes: the setup, three scrapers I built on different sites, how I run them on a schedule for free, and the places where it bit me.

Why a browser at all

My usual scraper is requests plus BeautifulSoup. It is fast and it is fine until the page builds its content with JavaScript. Then requests downloads an HTML shell with an empty <div> and a script tag, and your selectors find nothing.

The practice site quotes.toscrape.com has a /js/ version that is built exactly like that, so it is a fair test:

import requests
from bs4 import BeautifulSoup

html = requests.get("https://quotes.toscrape.com/js/").text
soup = BeautifulSoup(html, "html.parser")
print(len(soup.select(".quote")), "quotes found")   # 0 quotes found

The quotes are in the page when you open it in a browser. They are just not in the HTML. They live in a JavaScript array that a script writes into the DOM after load. You can dig the array out of the script tag with a regex, and I have done that more times than I would like to admit, but every site hides its data differently.

A headless browser skips the whole problem. It runs the page's JavaScript first, and then your code sees the same DOM you see in DevTools.

Terminal session: a Python script using requests finds 0 quotes on quotes.toscrape.com/js, while shot-scraper running in a real browser finds 10, and a pipeline through jq counts 8 unique authors
Same page, two answers. requests reads the HTML before any JavaScript runs, so it sees nothing. shot-scraper reads the page after it has run.

Setup

pip install shot-scraper
shot-scraper install      # downloads the Chromium build Playwright uses

The second command is easy to forget. Without it the first real command fails with a message about a missing browser executable.

The first test I always run:

shot-scraper javascript https://viraj-rana.github.io/site/ "document.title"

It prints a JSON string, quotes included. Any expression works, and if it returns an object or an array you get pretty-printed JSON back.

Scraper one: a book catalogue

books.toscrape.com is a fake bookshop made for practising scrapers, which makes it the polite place to learn. Every book on the listing page sits in an article.product_pod.

My workflow is always the same. Open the page, open the DevTools console, and build the expression there until the output looks right. Only then move it to the terminal. Here is where I ended up:

Array.from(document.querySelectorAll('article.product_pod'), el => {
  const link = el.querySelector('h3 a');
  const words = { One: 1, Two: 2, Three: 3, Four: 4, Five: 5 };
  const ratingClass = el.querySelector('p.star-rating').className.split(' ')[1];
  return {
    title: link.title,                       // the visible text is cut off with "..."
    url: link.href,                          // .href gives the absolute URL
    price: parseFloat(el.querySelector('.price_color').innerText.replace('£', '')),
    rating: words[ratingClass],
    inStock: el.querySelector('.availability').innerText.trim() === 'In stock'
  };
})

Two details in there cost me ten minutes each:

  • The title. The link text is truncated with an ellipsis for long titles. The full title is in the title attribute.
  • The rating. There is no number anywhere. The rating is a class name, star-rating Three, so I map the word to a number.

I keep the expression in its own file so my editor highlights it, then pass it in with $(cat ...):

shot-scraper javascript https://books.toscrape.com/ "$(cat books.js)" > books.json

Because the output is plain JSON, everything I already know about the shell just works. Cheap, well-rated books that are actually in stock:

jq -r '.[] | select(.rating >= 4 and .price < 30 and .inStock) | "\(.price)  \(.title)"' books.json

Scraper two: content that arrives late

Some pages fill in after load: a request fires, a spinner shows, and the data lands a second later. quotes.toscrape.com has a /js-delayed/ page that simulates exactly this. If you read the DOM as soon as the page loads, you get nothing.

shot-scraper waits if your expression returns a Promise. So I wait until the elements I need exist, with a timeout so a broken page cannot hang a scheduled job forever:

new Promise((resolve, reject) => {
  const started = Date.now();
  const timer = setInterval(() => {
    const quotes = document.querySelectorAll('.quote');
    if (quotes.length) {
      clearInterval(timer);
      resolve(Array.from(quotes, q => ({
        text: q.querySelector('.text').innerText.replace(/^“|”$/g, ''),
        author: q.querySelector('.author').innerText,
        tags: Array.from(q.querySelectorAll('.tag'), t => t.innerText)
      })));
    } else if (Date.now() - started > 15000) {
      clearInterval(timer);
      reject(new Error('no quotes after 15 seconds'));
    }
  }, 250);
})

Polling for the element is better than a fixed setTimeout. A fixed sleep is either too short on a slow day or wasted time on a fast one.

The reject matters too. When the JavaScript throws or the promise rejects, shot-scraper exits with a non-zero code. That is what makes the next part work.

Scraper three: a test for my own site

That exit code turns shot-scraper into a cheap smoke test. After every deploy of my site I want to know two things: the page has the right title, and the post list actually rendered.

const posts = document.querySelectorAll('.post-entry').length;
if (!document.title.includes('Viraj')) throw new Error('wrong title: ' + document.title);
if (posts < 5) throw new Error('only ' + posts + ' posts rendered');
posts;

The last line is the value that gets printed. If either check throws, the command fails and so does the CI job. It is not a replacement for a proper test suite. It catches the deploy where a broken build quietly ships an empty page.

Running it on a schedule with git scraping

A scraper that runs once is a curiosity. The useful version runs every day and remembers what changed. Simon calls the pattern git scraping: commit the JSON to a repository on every run, and Git becomes your change history for free. git log -p books.json shows every price change, every book that sold out.

GitHub Actions can run this without any server of mine. The workflow:

name: Scrape books

on:
  schedule:
    - cron: "17 6 * * *"     # daily at 06:17 UTC, off the busy hour
  workflow_dispatch:          # plus a button to run it by hand

permissions:
  contents: write             # needed to push the commit back

jobs:
  scrape:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          python-version: "3.10"
      - name: Install shot-scraper
        run: |
          pip install shot-scraper
          shot-scraper install
      - name: Scrape
        run: shot-scraper javascript https://books.toscrape.com/ "$(cat books.js)" > books.json
      - name: Commit if changed
        run: |
          git config user.name "scrape-bot"
          git config user.email "actions@users.noreply.github.com"
          git add books.json
          git diff --staged --quiet || git commit -m "books: $(date -u +%F)"
          git push

The git diff --staged --quiet || line is the important one. It only commits when the data actually changed, so the history stays a list of real changes instead of one empty commit a day.

The scrape step also fails loudly when a selector breaks, because the expression throws on a null. I get an email from GitHub that morning instead of a month of silently empty files.

Things that bit me

  • innerText against textContent. innerText respects CSS, so hidden elements come back empty and whitespace is collapsed the way it looks on screen. Usually that is what I want. When something is in the DOM but hidden, use textContent.
  • Quoting. The expression sits inside double quotes in the shell, so I write JavaScript with single quotes only. Keeping it in a .js file with $(cat file.js) avoids most of the pain.
  • Selectors drift. Sites change their markup. Scrape by the most meaningful hook you can find, like article.product_pod or a data- attribute, not div > div:nth-child(3).
  • Be polite. One request a day to a page is nothing. Looping over five thousand product pages from a CI runner is something else. Read the site's terms and robots.txt, keep the rate low, and use an official API when one exists. The two toscrape sites exist for practice, which is why I used them here.
  • Logins. Do not paste session cookies into a public repository's workflow. If a page needs an account, it probably should not be scraped from public CI at all.

Why I like this

The whole books scraper is one JavaScript expression, one shell command and a twenty-line workflow file. I wrote the scraping logic in the same console I use to debug my own front-end code, with autocomplete and the live page in front of me. There is no driver to manage, no waiting for elements in a second language, and no Selenium server.

A full browser is heavier than requests, and for static pages I still reach for requests first. But for anything built with JavaScript, it is the fastest route I have found from "I wonder if I could track that" to a JSON file that updates itself every morning.

Thanks to Simon Willison for the tool and his original write-up, which is worth reading too.