Recipes and Steps: A Small Architecture for Scraping Many Sites With Playwright

René Kulik on 01.12.2026

Introduction

One of my side projects watches about ten websites for new entries in a list. Every site is different. Some deliver the whole list in the HTML. Some hide it in a JSON blob inside a <script> tag. Some block plain HTTP requests and only answer a real browser. Some only show twenty entries until you click “load more” a few times. And one needs a login first.

My first version had one function per site that did everything: fetch, click, wait, parse. It worked for three sites. By the sixth, every function looked a little different, and fixing a bug in one did not fix it in the others.

In this post, I will show the structure I ended up with: every site is a short description made of reusable parts, and the parts that differ between sites are the only parts a site has to write.

One Folder per Site

Everything that belongs to a site lives in one folder:

src/sources/sites/<site>/
  source.ts              name, interval, URL, how the page is read, which parser
  <site>-parser.ts       turns the page into entries; selectors at the top
  schema.ts              the shape of the site's raw data
  <site>-parser.test.ts  test for the parser
  fixtures/              saved pages the test runs against
  .env.example           login sites only: the keys the site needs

When a site changes its markup, I open one folder. When I add a site, I add one folder. When I remove one, I delete it. Nothing outside the folder needs to know.

Reading and Parsing Are Separate Jobs

The most important split is between getting the page and understanding it. These two things change for different reasons. A site might move from server-rendered HTML to a JavaScript app, which changes how I read it but not what the entries look like. Or it might rename a CSS class, which changes the parser but not how I get the page.

So there are two interfaces:

export interface PageReader {
  read: (context: SourceContext) => Promise<string>;
}

export interface Parser {
  parse: (text: string) => RawListing;
}

A reader returns text: HTML, or JSON when a site has an API. A parser turns that text into entries. And a site is just the combination of the two:

export abstract class BaseSource implements Source {
  public abstract readonly id: string;
  public abstract readonly name: string;
  public abstract readonly intervalMinutes: number;
  protected abstract readonly reader: PageReader;
  protected abstract readonly parser: Parser;

  public async collect(context: SourceContext): Promise<RawListing> {
    return this.parser.parse(await this.reader.read(context));
  }
}

The SourceContext is how a site reaches the outside world: a function to fetch text, a function to get a browser page, and a function to read credentials. Sites never import Playwright or fetch directly, which makes them easy to test and lets the runner control things like timeouts and the user agent in one place.

Recipes: How a Page Is Read

There are two readers. I call them recipes, because they describe how to get to the finished page.

The simple one fetches a URL:

export class FetchRecipe implements PageReader {
  private readonly url: string;

  public constructor(url: string) {
    this.url = url;
  }

  public async read(context: SourceContext): Promise<string> {
    return context.fetchText(this.url);
  }
}

The other one opens a browser, runs a list of steps on the page, and returns the HTML once all steps are done:

export class BrowserRecipe implements PageReader {
  private readonly url: string;
  private readonly steps: PageStep[];

  public constructor(url: string, steps: PageStep[]) {
    this.url = url;
    this.steps = steps;
  }

  public async read(context: SourceContext): Promise<string> {
    return context.withPage(async (page) => {
      await page.goto(this.url, { waitUntil: 'networkidle' });

      for (const step of this.steps) {
        await step.run(page, context);
      }

      return page.content();
    });
  }
}

A site that only needs a plain request now looks like this:

const SEARCH_URL = 'https://www.example.com/search?sort=newest';

class ExampleSource extends BaseSource {
  public readonly id = 'example';
  public readonly name = 'Example';
  public readonly intervalMinutes = 15;
  protected readonly reader = new FetchRecipe(SEARCH_URL);
  protected readonly parser = new ExampleParser();
}

export const SOURCE: Source = new ExampleSource();

If the site starts blocking plain requests, only the reader line changes:

protected readonly reader = new BrowserRecipe(SEARCH_URL, []);

The parser does not change at all.

Steps: What Happens on the Page

A step is one thing to do on a page before it is read:

export interface PageStep {
  run: (page: Page, context: SourceContext) => Promise<void>;
}

I have three of them so far. Each one sounds trivial and each one had at least one surprise.

Clicking “Load More”

ClickUntilGoneStep clicks a button until it disappears. That was the plan, at least. In practice, the button disappears for a moment while the next batch loads, so “the button is gone” does not mean “everything is loaded”. And on the last page, some sites hide the button right between my visibility check and my click, so the click throws.

The step now counts the entries before each click and waits until there are more:

while (clicks < this.maxClicks && (await button.isVisible())) {
  const previousCount = await page.locator(this.itemSelector).count();

  try {
    await button.click({ timeout: CLICK_TIMEOUT_MS });
  } catch (error) {
    // The button often hides itself right after the last page has loaded, between the check and the click.
    if (await button.isVisible()) {
      throw error;
    }

    break;
  }

  if (!(await this.waitForMoreItems(page, previousCount))) {
    break;
  }

  clicks += 1;
}

If the list stops growing, the step stops. And maxClicks keeps a button that never goes away from running a check forever.

Using it is one line in the site’s recipe:

protected readonly reader = new BrowserRecipe(SEARCH_URL, [
  new ClickUntilGoneStep('button:has-text("Load more")', '.result-card'),
]);

Logging In Only When Needed

LogInStep fills a login form with credentials from the site’s own .env file. The important part is that it first checks whether the form is there at all:

public async run(page: Page, context: SourceContext): Promise<void> {
  if (!(await this.isVisible(page, this.options.formMarker))) {
    return;
  }

  // dismiss the cookie banner, fill the fields, submit, wait for the form to disappear
}

For login sites, the browser’s cookies are kept in a session file and loaded again on the next run. So most of the time, the session is still valid, the site shows the list directly, and the step does nothing. Only when the session has expired does the site redirect to the form, and the step logs in.

Two details made this reliable. The session is only saved after a successful run, so a failed login never replaces a working session. And the session file holds login cookies, so it is written with file mode 0600, readable only by my user.

Waiting for the Right Thing

WaitForStep waits for a selector. The surprise here was choosing what to wait for. One site renders its result counter before its results, and the counter is empty at first. Waiting for the counter meant reading the page before the list was there. The fix was to wait for either a result card or a counter that explicitly says zero:

new WaitForStep('.result-card, .result-count:text-is("0")');

The selector is now part of the site’s recipe, together with a short comment on why. That is the right place for it: it is knowledge about this one site, not about waiting in general.

Parsing Cards One by One

Most of the HTML sites have the same shape: a list of cards, one per entry. So there is a base parser for that shape. A site only says where its cards are, how to read one, and what a valid card looks like:

export abstract class CardListingParser<TCard> implements Parser {
  protected abstract readonly itemSelector: string;
  protected abstract readonly schema: z.ZodType<TCard>;

  public parse(html: string): RawListing {
    const document = parse(html);
    const cards = document.querySelectorAll(this.itemSelector);

    if (cards.length === 0) {
      throw new Error('List not found on the page');
    }

    const entries = cards.flatMap((card) => {
      const result = this.schema.safeParse(this.readCard(card));

      return result.success ? [this.createEntry(result.data)] : [];
    });

    return { entries, skippedCount: cards.length - entries.length };
  }

  protected abstract readCard(card: HTMLElement): unknown;

  protected abstract createEntry(card: TCard): RawEntry;
}

Every card is validated on its own with Zod. One odd card, a sponsored entry or one with a missing title, is skipped and counted. It does not take the other nineteen down with it. The skippedCount ends up in the check’s log, so I notice when a site suddenly skips half of its cards.

A site’s parser is then mostly a list of selectors:

const SELECTORS = {
  item: 'div.result-card',
  title: '.result-card__title',
  link: 'a.result-card__link',
  location: '.result-card__location',
};

export class ExampleParser extends CardListingParser<Card> {
  protected readonly itemSelector = SELECTORS.item;
  protected readonly schema = CardSchema;

  protected readCard(card: HTMLElement): unknown {
    return {
      title: card.querySelector(SELECTORS.title)?.text,
      url: card.querySelector(SELECTORS.link)?.getAttribute('href'),
      location: card.querySelector(SELECTORS.location)?.text,
    };
  }

  protected createEntry(card: Card): RawEntry {
    return { title: card.title, url: card.url, location: card.location };
  }
}

The selectors sit at the top of the file, because they are what breaks first.

A Broken Page Is Not an Empty Page

Notice the throw in the parser above. If there are no cards, the parser does not return an empty list. It fails.

That sounds strict, but the alternative is worse. When a site changes its markup, my selectors stop matching, and an empty list looks exactly like “nothing new today”. I would not notice for weeks. A failure shows up as a red status in the interface right away.

Some sites can genuinely have zero results, though. For those, the parser has an optional hook that recognizes the site’s own “no results” message:

protected isEmptyListing?(document: HTMLElement): boolean;

Only when the page says so itself is an empty list accepted as empty.

Finding Sites by Their Folder

There is no list of sites anywhere in the code. At startup, a registry reads the folders, imports each source.ts, and validates what it exports, again with Zod:

const SourceSchema = z.object({
  id: z.string().min(1),
  name: z.string().min(1),
  enabled: z.boolean(),
  intervalMinutes: z.number().int().min(1).max(1440),
  collect: z.custom<Source['collect']>((value) => {
    return typeof value === 'function';
  }, 'must be a function'),
});

It also checks that a site’s id matches its folder name. A site copied from another folder with the old id still in it fails at startup with a clear message instead of overwriting another site’s data later.

Testing Against Saved Pages

Scrapers are hard to test against the real site: it changes, it is slow, and it might not like being hit by a test suite. So every site folder has a fixtures/ folder with saved copies of the page, and the parser tests run against those:

When a site changes, I save the new page, the test fails, and I fix the selectors until it passes. The tests run with Node’s built-in test runner directly on the TypeScript files, so there is no build step in between.

Conclusion

Scraping many sites gets manageable once you separate what differs from what repeats. In my case, that means four ideas: a site is a reader plus a parser, a reader is a recipe of reusable steps, a parser validates each entry on its own, and a page without entries is an error unless it says otherwise.

Each site file now reads like a short description of how a human would use the site: open this page, log in if asked, click “load more” until it is gone, then read the cards. And when a site breaks, I know which of those parts to look at.