Skip to main content

Silk

Silk — a declarative, fully typed web scraping library for building resilient browser automations in Python.


PyPI version Python versions PyPI Downloads License Code style: black Type check: mypy Type check: pyright

Silk lets you write elegant, resilient scrapers as small typed pipelines. You describe what to extract; Silk handles the browser.

book = (
    Navigate(_, "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html")
    >> (GetText("h1", _) & GetText("p.price_color", _) & GetText("table td", _))
)
# Operation[Page, tuple[str, str, str]] — three reads, run concurrently
# Ok(('A Light in the Attic', '£51.77', 'a897fe39b1053632'))

Key Features

  • Composable DSL: Chain with >>, run in parallel with &, fall back with |.
  • Errors as values: Every run returns Ok(value) or Error(exception); nothing is swallowed.
  • Typed end to end: Pipelines are Operation[In, Out], checked by strict mypy and Pyright.
  • Immutable by design: Actions are frozen values with no hidden browser state.
  • Resilient: Selector fallback groups, retry, recovery, and explicit failure policies.
  • Schema-first extraction: Build dataclasses, Pydantic models, or dicts straight from the page.

First-Class Composition

Silk treats composition as a first-class citizen:

  • Actions as values: Browser actions are immutable operations you can store, pass, and combine.
  • Intuitive operators: Compose with >>, &, and | for pipelines that read top to bottom.
  • Composition is associative: (a >> b) >> c is the same pipeline as a >> (b >> c).
  • Modular architecture: Complex workflows emerge from small, reusable, independently tested pieces.
Operator Name Meaning
a >> b then Feed a's output into b
a & b fan out Run a and b on the same input concurrently, collect (a, b)
a | b or else If a fails, run b on the original input
from fp_ops import _

from silk.actions.elements import GetText, RequireAttribute, RequireElement
from silk.actions.navigation import Navigate

first_card = RequireElement("article.product_pod", _)
title = RequireAttribute("h3 > a", _, attribute="title")
price = GetText(".sale-price", _) | GetText("p.price_color", _)

first_book = (
    Navigate(_, "https://books.toscrape.com/")
    >> first_card
    >> (title & price)
)
# Operation[Page, tuple[str, str]]

Developer Experience

Actions are type-safe operations (Operation[In, Out]). Describe the shape; Silk does the work:

from dataclasses import dataclass

from fp_ops import _, build, traverse

from silk.actions.elements import GetText, QueryAll, RequireAttribute
from silk.actions.navigation import Navigate


@dataclass(frozen=True, slots=True)
class Book:
    title: str
    price: str


extract_book = build(  # dataclasses, Pydantic models, any class, or a plain dict
    {
        "title": RequireAttribute("h3 > a", _, attribute="title"),
        "price": GetText("p.price_color", _),
    },
    Book,
)

books = (
    Navigate(_, "https://books.toscrape.com/")  # load the page
    >> QueryAll("article.product_pod", _)       # list[ElementHandle]
    >> traverse(extract_book)                   # list[Book]
)
# Operation[Page, list[Book]]

Why it feels great:

  • Actions as values: Drop actions directly into a schema, with no glue code or lambdas.
  • Types flow through: Your editor knows books produces list[Book] before it runs.
  • Honest failures: A failed field reports which item and which field, with the original browser error attached.

Silk also provides utilities such as selector groups for handling fallbacks:

from silk.selectors import SelectorGroup, css, xpath

title_selector = SelectorGroup(
    "book_title",
    css("h3 > a[title]"),
    css(".product_pod h3 a"),
    xpath("//article[contains(@class, 'product_pod')]//h3/a"),
)
price_selector = SelectorGroup(
    "book_price",
    css("p.price_color"),
    xpath("//p[contains(@class, 'price')]"),
)

extract_book = build(
    {
        "title": RequireAttribute(title_selector, _, attribute="title"),
        "price": GetText(price_selector, _),
    },
    Book,
)

Declarative API

Silk embraces declarative programming that focuses on what to accomplish, not how:

# Imperative: HOW to read the first book
await page.goto("https://books.toscrape.com/")
card = await page.query_selector("article.product_pod")
if card is None:
    raise LookupError("no product card")
link = await card.query_selector("h3 > a")
title = await link.get_attribute("title") if link else None
price_element = await card.query_selector("p.price_color")
price = await price_element.text_content() if price_element else None

# Declarative: WHAT to read with Silk
first_book = (
    Navigate(_, "https://books.toscrape.com/")
    >> RequireElement("article.product_pod", _)
    >> (RequireAttribute("h3 > a", _, attribute="title") & GetText("p.price_color", _))
)

Missing elements and attributes become explicit ElementNotFoundError and AttributeNotFoundError values instead of None checks scattered through your code.

Installation

pip install silk-scraper
python -m playwright install chromium

Linux CI images usually also need Playwright's system packages:

python -m playwright install --with-deps chromium

Quick Start

import asyncio

from fp_ops import _

from silk.actions.elements import GetText, RequireAttribute
from silk.actions.navigation import Navigate
from silk.browsers.models import BrowserOptions
from silk.browsers.sessions import BrowserSession

pipeline = (
    Navigate(_, "https://books.toscrape.com/")
    >> (
        GetText("li.current", _).map(str.strip)
        & RequireAttribute("h3 > a", _, attribute="title")
    )
)


async def main() -> None:
    async with BrowserSession(options=BrowserOptions(headless=True)) as session:
        result = await pipeline.run(session.page, environment=session.environment)

        if result.is_ok():
            page_label, first_title = result.ok
            print(f"{page_label}: {first_title}")  # Page 1 of 50: A Light in the Attic
        else:
            print(f"Error: {result.error}")


if __name__ == "__main__":
    asyncio.run(main())

BrowserSession owns the browser, its first context, and its first page. The page goes in as the pipeline's input; the browser is shared through the read-only session.environment.

Core Concepts

Actions

Actions are the building blocks of your scraping logic. Each action:

  • is an immutable, typed Operation[In, Out] built when you call it;
  • takes exactly one input, marked by the _ placeholder;
  • returns a Result, either Ok(value) or Error(exception), when run.

The _ decides which argument is the pipeline input. Everything else is configuration fixed at construction:

GetText("h1", _)           # input: the page or element to search in
GetText(_, card)           # input: the selector or element to read
Drag(_, basket)            # input: the element being dragged
Drag(book, _)              # input: the drop target

Run any pipeline with exactly one value:

result = await pipeline.run(session.page, environment=session.environment)

Sequential Operations (>>)

>> feeds each step's output into the next. Actions move the focus forward: querying returns an element, so the next step is scoped to it.

add_first_book_to_basket = (
    Navigate(_, "https://books.toscrape.com/")   # Page
    >> RequireElement("article.product_pod", _)  # that book's card
    >> Click("button.btn-primary", _)            # its own "Add to basket"
)

Plain Python functions join a pipeline with @operation:

from fp_ops import operation


@operation
def parse_price(text: str) -> float:
    return float(text.removeprefix("£"))


price = GetText("p.price_color", _) >> parse_price  # Operation[ElementScope, float]

Parallel Operations (&)

& runs branches concurrently on the same input and collects their results into one flat tuple, in declaration order:

summary = (
    GetText("form.form-horizontal strong", _).map(int)  # total results
    & GetText("li.current", _).map(str.strip)           # pager label
    & QueryAll("article.product_pod", _).map(len)       # books on this page
)
# Operation[ElementScope, tuple[int, str, int]] -> Ok((1000, 'Page 1 of 50', 20))

a & b & c yields (a, b, c). A branch that itself returns a tuple stays a single value, and a & (b & c) nests as (a, (b, c)). If any branch fails, the others are cancelled and the error is returned.

For truly independent work, give each branch its own page:

from fp_ops import Operation

from silk.actions.browser import NewPage
from silk.browsers.models import BrowserContext

CATALOGUE = "https://books.toscrape.com/catalogue"


def book_title(slug: str) -> Operation[BrowserContext, str]:
    return NewPage(_) >> Navigate(_, f"{CATALOGUE}/{slug}/index.html") >> GetText("h1", _)


titles = (
    book_title("a-light-in-the-attic_1000")
    & book_title("tipping-the-velvet_999")
    & book_title("soumission_998")
)

result = await titles.run(session.context, environment=session.environment)
# Ok(('A Light in the Attic', 'Tipping the Velvet', 'Soumission'))

Fallback Operations (|)

| tries an alternative, with the original input, when the first operation fails:

price = GetText(".sale-price", _) | GetText(".regular-price", _) | GetText("p.price_color", _)

Fallbacks combine with every other operator. Each strategy below is a whole pipeline, and the first one to succeed wins:

from fp_ops import constant

page_label = GetText("li.current", _).map(str.strip) | constant("Page 1 of 1")

title = (
    RequireAttribute("h3 > a", _, attribute="title")      # full title attribute
    | GetText("h3 > a", _)                                # truncated link text
    | constant("Untitled")                                # last resort
)

| gives up on any failure, including browser errors. Use selector groups when only the selector should vary, and | when the whole strategy should.

Resilience

Every policy has a truthful name, so failure behavior is visible in the code:

from fp_ops import default_on_error, recover, retry

price = (
    retry(GetText("p.price_color", _), attempts=3, backoff=0.5)  # 3 tries in total
    | GetText(".price", _)
    | constant("unknown")
)

title = default_on_error(GetText("h1", _), "untitled")
length = recover(GetText("h1", _).map(len), lambda error: 0)
Work Fail fast Keep every result Keep successes
Parallel branches a & b / fanout_parallel fanout_all_settled —
Collection items traverse / traverse_parallel traverse_all_settled traverse_lossy
Object fields build build_all_settled build_lossy
Predicates filter_operation — filter_best_effort

Failures keep their causes. If one field of one book fails, the error reads:

TraversalItemError(index=3)
  -> BuildFieldError(field="title")
     -> original browser exception

Collections and Objects

Silk's collection and object helpers come from FP-Ops and work directly with actions:

from fp_ops import filter_each, traverse, traverse_parallel


def under_20(price: float) -> bool:
    return price < 20


cards = QueryAll("article.product_pod", _)

books = cards >> traverse_parallel(extract_book, limit=5)               # list[Book]
prices = cards >> traverse(GetText("p.price_color", _) >> parse_price)  # list[float]
bargains = prices >> filter_each(under_20)                              # list[float]

build constructs any class (dataclasses, Pydantic models, …) or, without one, a plain dict. Collection results always preserve input order.

Creating Custom Actions

Turn any function into an action with a configurable template. The _ marks the input, just like Silk's own actions:

from fp_ops import operation_template


@operation_template
def strip_prefix(prefix: str, text: str) -> str:
    return text.removeprefix(prefix)


price = GetText("p.price_color", _) >> strip_prefix("£", _) >> parse_price

result_operation_template returns a Result directly, and environment_result_operation_template(BROWSER) receives the running browser:

from fp_ops import Result, environment_result_operation_template

from silk.browsers.models import BROWSER, Browser, BrowserContext, BrowserContextOptions


@environment_result_operation_template(BROWSER)
async def isolated_context(
    options: BrowserContextOptions,
    browser: Browser,
) -> Result[BrowserContext, Exception]:
    return await browser.new_context(options)

Browser Configuration

from silk.actions.navigation import NavigateOptions
from silk.browsers.models import (
    BrowserContextOptions,
    BrowserOptions,
    BrowserProxy,
    BrowserViewport,
)
from silk.browsers.sessions import BrowserSession

options = BrowserOptions(
    headless=False,  # show the browser while debugging
    timeout=10_000,
    args=("--disable-gpu",),
    proxy=BrowserProxy(server="http://proxy.example:8080"),
)

context_options = BrowserContextOptions(
    viewport=BrowserViewport(width=1280, height=800),
    extra_http_headers={"accept-language": "en"},
    navigation_timeout=10_000,
)

navigate = Navigate(
    _,
    "https://books.toscrape.com/",
    options=NavigateOptions(wait_until="domcontentloaded"),
)

async with BrowserSession(options=options) as session:
    ...

Every option type is frozen. Each action has its own options (ClickOptions, FillOptions, WaitOptions, DragOptions, …), and later changes to your own lists or dicts can never retarget an action you already built.


API Reference

Module Structure

silk/
├── actions/
│   ├── browser.py      # contexts and pages (CreateContext, NewPage, Pages, …)
│   ├── elements.py     # lookup and extraction (Query, GetText, ExtractTable, …)
│   ├── input.py        # pointer, keyboard, and forms (Click, Fill, Drag, …)
│   └── navigation.py   # navigation and page data (Navigate, Title, Screenshot, …)
├── browsers/
│   ├── models.py       # Browser/Page/ElementHandle interfaces, BROWSER key, options
│   ├── sessions.py     # BrowserSession, the browser lifecycle owner
│   └── drivers/        # the Playwright adapter
├── selectors/          # Selector, SelectorGroup, css, xpath, text
└── errors.py           # ElementNotFoundError, AttributeNotFoundError, …

Composition (>>, &, |), Result, _, and the collection, object, and policy combinators come from FP-Ops.

Actions

Area Actions
Browser CreateContext, NewPage, Pages, PageById, ClosePage, CloseContext
Navigation and page data Navigate, GoBack, GoForward, Reload, WaitForNavigation, CurrentUrl, Title, Content, Screenshot, ScreenshotTo, Evaluate, EvaluateWith
Elements and extraction Query, RequireElement, QueryAll, GetText, GetInnerText, GetAttribute, RequireAttribute, GetHtml, ElementExists, WaitForElement, ExtractTable
Pointer, keyboard, and forms Click, DoubleClick, Fill, TypeText, SelectValue, SelectText, ScrollIntoView, ScrollTo, MouseMove, MouseMoveTo, MouseDown, MouseUp, KeyPress, KeyDown, KeyUp, Drag
  • Query returns None when nothing matches; RequireElement returns ElementNotFoundError.
  • GetAttribute returns None for a missing attribute; RequireAttribute returns AttributeNotFoundError.
  • Element actions such as Click and Fill return the element they acted on; page actions such as KeyPress and Navigate return the page.
  • WaitForNavigation waits for the next main-frame navigation, not the current one.

Selectors

  • css(value), xpath(value), text(value) create a selector; plain strings are CSS.
  • SelectorGroup(name, *selectors) tries each selector in order. A browser error stays an error and is never mistaken for "not found".

Sharing a page

& and the parallel helpers give every branch the same input and browser; they never clone a page or element. Concurrent reads of one page are safe. For concurrent clicks, typing, or navigation, give each branch its own page with NewPage or its own context with CreateContext. A limit bounds how many tasks run at once, but it does not isolate them.


Roadmap

  • Initial release with Playwright support
  • Improve manager ergonomics
  • Mapped tasks over collections (QueryAll >> traverse(...))
  • Run multiple actions on one page ergonomically (GetText & GetAttribute & GetHtml)
  • Typed action signatures, checked by mypy and Pyright
  • Proxy options
  • Selenium integration
  • Puppeteer integration
  • Explore stealth options (Patchright, nodriver, …)
  • Support computer-using agents (browser-use, OpenAI CUA, Claude computer use)
  • Enhanced caching
  • Distributed scraping
  • Rate limiting and polite scraping utilities
  • Integrations with data and scraping libraries (Pandas, Scrapy, …)

Development

poetry install --with dev
poetry run playwright install --with-deps chromium
poetry run pre-commit run --all-files
poetry run python -m pytest tests -v
poetry run mypy
poetry run pyright
poetry run python tests/typecheck/check_bad_fixtures.py --all-python-versions

The suite includes live Chromium tests, the real Books to Scrape example, and an installed-wheel smoke test. After an intentional public typing change, refresh the negative type-check contract with poetry run python tests/typecheck/check_bad_fixtures.py --write-contract.

License

Silk is available under the MIT License.

Metadata

Release files for silk-scraper 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for silk-scraper 0.4.0
File Size Uploaded Provenance Actions
silk_scraper-0.4.0.tar.gz 28.9 kB Without provenance Details for silk_scraper-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for silk-scraper 0.4.0
File Interpreter ABI Platform Actions
silk_scraper-0.4.0-py3-none-any.whl Python 3 none any Details for silk_scraper-0.4.0-py3-none-any.whl

Total release size: 58.1 kB

Release files / silk_scraper-0.4.0.tar.gz

Download URL silk_scraper-0.4.0.tar.gz
Size 28.9 kB
Tags Source
SHA-256 checksum
How to use checksums
0637f8936aa6b45097ccdf6dce733b3b3965e53568fbd0e6ebf618bb5716b6fa
BLAKE2b-256 checksum
How to use checksums
8944dcbac73f7d9134517a64db1df2e59b4d84a39f80615f02eaf6d3bb693183
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / silk_scraper-0.4.0-py3-none-any.whl

Download URL silk_scraper-0.4.0-py3-none-any.whl
Size 29.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8a207bac249720ef92b7493c133488a5a0119f5bcb394e4265a0d29ffebc1f04
BLAKE2b-256 checksum
How to use checksums
5796bbeb94125ffc8a2ece72f30ad0630faa5ac7a1bbdd11281ac21553ce34f9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for silk-scraper 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page