Skip to content

Deep Crawling & Seeding

A deep crawl starts from one or more seed URLs and follows links. PAM Crawl keeps a frontier of discovered links, decides which ones to visit (filters), in which order (strategies and scorers) and when to stop (depth, page limits, or confidence in adaptive mode).

Sometimes you do not want to follow links at all. Seeding tools discover URLs from sitemaps, the Common Crawl index or a domain’s well-known paths, and rank them before anything is downloaded.

Crawl::site() creates a deep crawl with sensible defaults: same host only, breadth-first, depth 3, at most 1,000 pages, robots.txt respected, and static assets and “nonsense” URLs (admin, login, cart, search, print views, feeds) skipped.

tutorial.php
use Pam\Crawl\Crawl;
use Pam\Crawl\Page;
$count = Crawl::site('https://docs.python.org/3/tutorial/index.html')
->only('/3/tutorial/*') // stay inside the tutorial
->ignoreQueryStrings()
->depth(2) // the seed is depth 0
->limit(15) // stop after 15 pages
->concurrency(4, perHost: 4)
->each(function (Page $page): void {
printf("d%d %d %s <- %s\n", $page->depth, $page->status, $page->url, $page->parent ?? '(seed)');
});

Every page knows its depth and the parent page that linked to it. Pass several seeds to Crawl::site() to start from more than one page.

Method Description
depth(int $maxDepth) Maximum link depth. The seed is depth 0. Default 3.
limit(int $maxPages) Maximum number of pages. Default 1000.
only(string ...$patterns) Follow only URLs matching any pattern.
except(string ...$patterns) Never follow URLs matching any pattern.
filterUrls(UrlFilter ...$filters) Add custom URL filters.
strategy(Strategy $strategy) Strategy::BreadthFirst (default), DepthFirst or BestFirst.
prioritize(Scorer $scorer, float $threshold = -INF) Best-first: visit the highest-scoring links first.
includeSubdomains() Follow links to any subdomain of the seed’s registrable domain.
followExternal() Follow links to any host.
sitemap() Also seed the frontier from robots.txt and sitemap.xml.
ignoreQueryStrings() Treat URLs that differ only in their query string as the same page.

only(), except() and when() share the same pattern syntax (Crawl4AI’s URLPatternFilter):

Pattern Matches
/docs/* A path prefix.
*.html An extension.
^https://example\.com/a/\d+$ A regular expression, when it starts with ^.
*/blog/**, */{guide,api}/* A glob over the full URL. ** spans any depth, {a,b} is alternation.

For anything patterns cannot express, combine filters from Pam\Crawl\Frontier\Filter:

use Pam\Crawl\Frontier\Filter;
$crawler = Crawl::site('https://example.com/')
->filterUrls(
Filter::domains(allowed: ['example.com'], blocked: ['ads.example.com']),
Filter::types('html', 'pdf'),
Filter::using(fn ($candidate) => !str_contains($candidate->url, '/archive/')),
);
Filter Description
Filter::patterns(string ...$patterns) Same as only(). Call ->not() on any filter to invert it.
Filter::domains(array $allowed = [], array $blocked = []) Allow or block hosts.
Filter::types(string ...$kinds) Allowed content kinds by extension: html, pdf, json, xml, text, image. Extension-less URLs pass.
Filter::noAssets() Skip static assets and binaries. On by default for site().
Filter::noNonsense() Skip admin, login, cart, search, print and similar URLs. On by default for site().
Filter::using(callable $fn) Your own predicate. It receives a Frontier\Candidate with url, depth, parent, anchor and context.

Two filters look at the target page’s <head> before it is crawled. Heads are fetched concurrently and cached:

  • new Frontier\ContentRelevanceFilter('async tasks', threshold: 2.0) keeps links whose head is relevant to a query (BM25).
  • new Frontier\SeoFilter(threshold: 0.65, keywords: ['php']) keeps links whose head scores well on title length, keywords, meta description, canonical, robots, schema.org data and URL quality.

Breadth-first visits links in discovery order. Best-first visits the most promising links first, which matters when you have a page budget. prioritize() switches the strategy to best-first and sets the scorer:

best-first.php
use Pam\Crawl\Crawl;
use Pam\Crawl\Frontier\Score;
$crawler = Crawl::site('https://www.php.net/manual/en/book.array.php')
->only('/manual/en/*')
->depth(2)
->limit(10)
->prioritize(Score::all(
Score::keywords('sort', 'array', 'usort')->weight(1.0),
Score::depth(optimal: 1)->weight(0.2),
));
foreach ($crawler->stream() as $page) {
printf("%.2f %s\n", $page->response->request->score, $page->meta->title);
}

Scorers live in Pam\Crawl\Frontier\Score and port Crawl4AI’s URL scorers. Each can be weighted with ->weight():

Scorer Scores
Score::keywords(string ...$keywords) Share of keywords present in the URL or the link’s anchor text.
Score::depth(int $optimal = 3) Closeness to an optimal path depth.
Score::freshness(?int $currentYear = null) The newest year found in the URL.
Score::contentType(array $weights) Extension (.pdf) or regex to weight.
Score::domains(array $weights, float $default = 0.5) Domain to weight.
Score::intrinsic() Link quality from the URL and anchor text alone (0 to 10).
Score::all(Scorer ...$scorers) Normalized average of several scorers.
Score::using(callable $fn) Your own function of a Frontier\Candidate.

The threshold argument of prioritize() drops links that score below it.

when() applies content options to URLs that match a pattern, inside one crawl. The first matching rule wins. Transport options (concurrency, proxies, cache) stay global:

rules.php
use Pam\Crawl\Crawl;
use Pam\Crawl\Crawler;
$pages = Crawl::site('https://books.toscrape.com/')
->limit(20)
->when('*/catalogue/category/*', fn (Crawler $c): Crawler => $c->target('ol.row')->withoutImages())
->when('*/catalogue/*/index.html', fn (Crawler $c): Crawler => $c->selector('article.product_page'))
->all();

when() also accepts any UrlFilter instead of a pattern.

onPage() registers a callable that sees every page before it is yielded, like Crawl4AI’s after_request hook. Exporters and Stats are hooks (see Exporting). To stop a crawl early, return false from the each() callback, or simply break out of a stream() loop.

->sitemap() adds every URL from the site’s sitemaps (found through robots.txt or /sitemap.xml) to a deep crawl’s frontier. To read sitemaps without crawling, use the URL seeder.

Seed\UrlSeeder ports Crawl4AI’s AsyncUrlSeeder. It lists a domain’s URLs from its sitemaps and/or the Common Crawl index, optionally fetches only each page’s <head>, and ranks the URLs by BM25 relevance to a query, all without downloading a single page body:

seed.php
use Pam\Crawl\Crawl;
use Pam\Crawl\Seed\UrlSeeder;
$seeder = UrlSeeder::for('www.php.net')
->sources('sitemap') // 'sitemap', 'cc' or 'sitemap+cc'
->hitsPerSecond(10) // at most 10 requests per second
->cache(sys_get_temp_dir().'/seeder');
$all = $seeder->urls(); // discovery only
$ranked = $seeder
->extractHead() // fetch every <head>
->query('PHP changelog')
->scoreThreshold(0.2)
->urls();
foreach (array_slice($ranked, 0, 8) as $seed) {
printf("%.2f %s %s\n", $seed->score, $seed->url, $seed->head?->title);
}
// Then crawl only the best matches:
Crawl::urls(array_map(fn ($seed) => $seed->url, array_slice($ranked, 0, 20)))->each(fn ($page) => null);

Each result is a Seed\SeedUrl with url, status, head, score, source, originalUrl and error. Other options: pattern(string $glob), liveCheck(), limit(), concurrency(), timeout(), filterNonsense(), force() (ignore the cache) and stream() (a generator instead of a list). UrlSeeder::list($urls) scores a list of URLs you already have, and many($domains) seeds several domains.

Seed\DomainMapper maps a domain without crawling it, by merging several discovery sources: sitemap, robots, homepage links, feed, probe (common paths, with soft-404 detection), cc (Common Crawl), wayback and crt (certificate transparency, for subdomains):

map.php
use Pam\Crawl\Seed\DomainMapper;
$urls = DomainMapper::for('quotes.toscrape.com')
->sources('robots+homepage+probe')
->probePaths('/', '/login', '/about')
->includeSubdomains(false)
->hitsPerSecond(10)
->limit(15)
->scan();
foreach ($urls as $seed) {
echo $seed->url, ' found by ', $seed->source, "\n"; // e.g. "homepage+probe"
}

DomainMapper also offers query(), scoreThreshold(), extractHead(), soft404(), commonSubdomains(), maxPerSource(), timeouts() and cache().

Seed\LinkPreview scores the links of a page you already crawled, fetching each target’s <head> concurrently (Crawl4AI’s link_preview). Scores combine an intrinsic score (anchor text, URL shape, attributes) with BM25 relevance to an optional query:

use Pam\Crawl\Seed\LinkPreview;
$links = LinkPreview::of($page)
->query('love quotes')
->maxLinks(10)
->links();
foreach ($links as $link) {
printf("%.2f %s %s\n", $link->totalScore, $link->url, $link->head?->title);
}

An adaptive crawl answers “have I read enough about this?”. Give it a start URL and a question; it follows the most promising links only until the collected pages cover the question well, measured by coverage, consistency and saturation:

adaptive.php
use Pam\Crawl\Adaptive\AdaptiveCrawler;
use Pam\Crawl\Adaptive\Config;
$adaptive = new AdaptiveCrawler(new Config(
confidenceThreshold: 0.7,
maxPages: 10,
maxDepth: 2,
topKLinks: 3,
));
$state = $adaptive->digest(
'https://docs.python.org/3/library/asyncio.html',
'how to cancel an asyncio task with a timeout',
);
printf("confidence %.2f, sufficient: %s\n", $adaptive->confidence(), $adaptive->isSufficient() ? 'yes' : 'no');
print_r($adaptive->coverageStats()); // coverage, consistency, saturation...
print_r($state->crawlOrder); // pages visited, in order
foreach ($adaptive->relevantContent(3) as $hit) {
echo $hit['score'], ' ', $hit['url'], "\n"; // also: content
}

Adaptive\Config defaults to the statistical strategy, with maxPages: 20, maxDepth: 5, topKLinks: 3 and confidenceThreshold: 0.7. The embedding strategy measures coverage semantically with an embeddings model; see LLM Features. exportKnowledgeBase() and importKnowledgeBase() save and restore what was learned, and digest() accepts a resumeFrom state path.

Watch\Watcher snapshots pages in SQLite (ext-pdo_sqlite) and reports what changed between checks, line by line:

watch.php
use Pam\Crawl\Crawl;
use Pam\Crawl\Watch\Watcher;
$watcher = new Watcher(
Crawl::urls(['https://example.com/', 'https://example.com/pricing'])->cache(false),
'.cache/pam-crawl-watch.sqlite',
);
foreach ($watcher->check() as $diff) {
if ($diff->firstSeen) {
echo "{$diff->url}: first seen\n";
} elseif ($diff->changed()) {
echo "{$diff->url}: +", count($diff->added), ' / -', count($diff->removed), "\n";
echo $diff->summary(4), "\n";
}
}

By default the watcher compares each page’s main-content Markdown. Pass a view closure to compare something else (a price, a JSON field), and ignoreNumbers: true to ignore changes in numbers.

For a long-running monitor, every() loops and calls you only for real changes. It is a natural fit for a PAM worker or a systemd service:

$watcher->every(3600, function ($diff): void {
notify($diff->summary());
});

This product includes software developed by UncleCode (https://x.com/unclecode) as part of the Crawl4AI project (https://github.com/unclecode/crawl4ai).