# HarvestNet A self-healing web scraping and crawling framework for .NET. Every time a site you scrape changes its markup, your selectors break and your pipeline goes quiet until someone notices and fixes it by hand. HarvestNet adds an optional layer that catches this automatically: when a CSS selector stops matching, it hands the page to a free-tier LLM, asks for a replacement selector, checks that the replacement actually works, and remembers the fix so it never has to ask again for that field on that site. Python has had this kind of tooling for a while (Scrapy, Scrapling, Crawlee and others). .NET has not: outside of raw HTML parsers like AngleSharp and HtmlAgilityPack, there has been no actively maintained, AI-assisted scraping framework built for C#. HarvestNet is an attempt to close that gap. ## Why this exists Scraping code rots. A site redesigns its product cards, renames a CSS class, or wraps a price in a new ``, and every scraper pointed at that page silently starts returning nulls. Most teams find out when a report looks wrong, not when it happens. HarvestNet does not eliminate this problem, but it gives you a way to recover from it automatically instead of dropping everything to go read the new page source. The healing step only runs when extraction actually fails, so a healthy scrape that keeps matching all its selectors never calls an LLM at all. Combined with a free tier like Groq's, this means the AI-assisted part of HarvestNet effectively costs nothing for most projects. ## Features - **Polite crawling by default**: per-host rate limiting, robots.txt checks, automatic retries with exponential backoff (or the server's own Retry-After header) on 429 and 5xx responses, and configurable concurrency. - **Two ways to define what to extract**: a typed C# class with `[HarvestField]` attributes for compile-time safety, or a JSON field map for cases where the schema is only known at run time (this is what the CLI uses). - **CSS selectors, XPath, JSON-LD, or regular expressions** for any field, mixed freely within the same item. JSON-LD reads a page's schema.org structured data directly, which tends to be far more stable than the visible HTML. - **Self-healing selectors**, powered by your choice of Groq, Gemini, a local Ollama model, or any OpenAI-compatible endpoint, with automatic fallback across multiple providers if you chain them. Healed selectors are cached to disk per host and field, so the cost of a fix is paid once. - **Optional browser rendering** through HarvestNet.Browser (Playwright), for pages that need JavaScript to produce their final HTML. - **GET and POST requests**, including form submissions, plus an optional login step so pages behind a sign-in can be reached. - **Fallback selectors per field**, tried before self-healing kicks in, for sites that serve more than one page template for the same kind of content. - **A field transform pipeline** (trim, upper/lowercase, collapse whitespace, strip currency symbols or non-digit characters) so the CLI's schema-less output is clean without needing a custom C# class. - **A heuristic main-content extractor** for article and blog pages, similar to a browser's reader mode, for getting clean article text with no selector at all. - **Field coverage reporting**: every run reports what fraction of items actually had a value for each field, an easy way to notice a selector quietly failing on part of a site. - **Per-domain concurrency limits and adaptive throttling**: cap requests per host on top of the overall concurrency limit, and optionally let the delay for a host grow automatically after failures and relax back down after a run of successes. Robots.txt Crawl-delay directives are honored too. - **Ready-made schema.org models** (`SchemaOrgProduct`, `SchemaOrgArticle`) for scraping JSON-LD compliant product and article pages with zero selectors. - **Automatic pagination detection** (`PaginationHelper`) for the common "next page" link patterns, when you would rather not hand write one. - **Resumable crawls**: enable a checkpoint file and an interrupted run picks up where it left off instead of starting over. - **Proxy and User-Agent rotation** across a pool, with shared credentials for gateway style proxy providers. - **Response caching**, so iterating on selectors does not mean re-fetching the same pages over and over. - **Smart URL deduplication**, ignoring tracking parameters, fragments and trailing slashes when deciding whether a page has already been visited, plus optional item level deduplication for content that appears more than once. - **Sitemap.xml or plain text file seeding**, so a crawl can discover its URLs instead of listing them all by hand. - **Live progress reporting** through a simple `IProgress` callback. - **Change tracking**: `harvestnet diff` compares two runs, and `harvestnet watch` re-runs a recipe on a schedule and reports what changed, optionally notifying a webhook. - **Three output sinks** out of the box: JSON Lines, CSV and SQLite, all safe under concurrent writes. - **A CLI with no code required**: describe a scrape as a JSON recipe and run it with `harvestnet run recipe.json`, check it first with `harvestnet validate`, try a single selector against a live page with `harvestnet test-selector`, or summarize an existing output file with `harvestnet stats`. - **A clean library API** for anything more custom: build a `HarvestSpider`, add seed URLs, wire up sinks and a link extractor, and call `RunAsync()`. ## Installation ### As a library ```bash dotnet add package HarvestNet.Core ``` To scrape JavaScript-rendered pages, also add the browser rendering package and install Playwright's browser binaries once per machine: ```bash dotnet add package HarvestNet.Browser dotnet tool install --global Microsoft.Playwright.CLI playwright install chromium ``` ### As a command line tool ```bash dotnet tool install --global HarvestNet.Cli ``` This installs the `harvestnet` command. (Both packages are not yet published to NuGet as of this writing. See the "Publishing" section below for how to push them from this repository.) ## Quick start: the library ```csharp using HarvestNet.Core; using HarvestNet.Core.Export; using HarvestNet.Core.Extraction; public class Quote { [HarvestField(".text")] public string? Text { get; set; } [HarvestField(".author")] public string? Author { get; set; } } var spider = new HarvestSpider() .AddSeedUrl("https://quotes.toscrape.com/") .WithItemSelector(".quote") .WithSink(new CsvSink("quotes.csv")); var summary = await spider.RunAsync(); Console.WriteLine($"Extracted {summary.ItemsExtracted} quotes from {summary.PagesFetched} pages."); ``` Run the full version of this example, including pagination, from `samples/QuickStart`. ## Quick start: the CLI Generate a starter recipe: ```bash harvestnet init my-scrape ``` Edit `my-scrape.json`: ```json { "seedUrls": ["https://quotes.toscrape.com/"], "itemSelector": ".quote", "fields": { "text": { "selector": ".text" }, "author": { "selector": ".author" } }, "linkSelector": "li.next > a", "maxDepth": 5, "maxPages": 50, "output": { "format": "json", "path": "quotes.jsonl" } } ``` Run it: ```bash harvestnet run my-scrape.json ``` A more complete example, including self-healing, lives in `samples/recipes/quotes-example.json`. ## Turning on self-healing Self-healing is optional and off by default. It needs one LLM provider, all of which have a free tier or run entirely locally. | Provider | Cost | Setup | |---|---|---| | Groq | Free tier | Create an API key at console.groq.com | | Gemini | Free tier | Create an API key at aistudio.google.com | | Ollama | Free, local | Install Ollama and pull a model, e.g. `ollama pull llama3.1` | | Any OpenAI-compatible endpoint | Depends on the provider | Point it at OpenRouter's free models, LM Studio, or your own server | In code: ```csharp using HarvestNet.Core.Healing; var healer = new SelectorHealer( new GroqHealingProvider(Environment.GetEnvironmentVariable("GROQ_API_KEY")!), new HealingCache()); var spider = new HarvestSpider() .AddSeedUrl("https://quotes.toscrape.com/") .WithItemSelector(".quote") .WithHealing(healer) .WithSink(new CsvSink("quotes.csv")); ``` In a recipe: ```json { "healing": { "provider": "groq", "apiKey": "env:GROQ_API_KEY", "model": "llama-3.3-70b-versatile" } } ``` `apiKey` accepts either a literal key or `env:VARIABLE_NAME` to read it from an environment variable at run time, so you never have to commit a key to a recipe file. If you have a paid API key for a stronger model, you can use it too: `GeminiHealingProvider` and `OpenAiCompatibleHealingProvider` both work with any model name your account has access to. HarvestNet never requires a paid key; it just does not get in the way if you have one. Chaining providers is also supported, so a fast API can fall back to a local model: ```csharp var healer = new SelectorHealer( new HealingProviderChain( new GroqHealingProvider(groqApiKey), new OllamaHealingProvider()), new HealingCache()); ``` In a recipe, chain providers with a comma: `"provider": "groq,ollama"`. Note that a recipe's `apiKey` and `model` are shared across every provider in the chain, so this only works cleanly when at most one provider in the chain actually needs a key (Ollama does not). For chains where each provider needs its own key or model, build the chain in code instead. ## JSON-LD, XPath and regular expressions Many modern sites embed schema.org structured data in a `