Merge pull request #820 from internetarchive/browser-docs

Document browser-based crawling
This commit is contained in:
Alex Osborne authored and GitHub committed 2026-11-14 01:17:03 +09:00
commit da6489beee
7 files changed
+225 -19

No files matched your search

+183
View File
@@ -937,6 +937,189 @@ the whois fetcher will attempt to resolve ``whois:archive.org`` and ``whois:207.
At this time, whois functionality is experimental. The fetchWhois bean is commented out in the default profile.
Browser-based Crawling
----------------------
Heritrix can load the pages it fetches in a web browser to capture resources that can only be discovered by executing
JavaScript. The browser is controlled using the standard `WebDriver BiDi <https://developer.mozilla.org/en-US/docs/Web/WebDriver/Reference/BiDi>`_
protocol, supported by Firefox natively and Chrome via `ChromeDriver <https://developer.chrome.com/docs/chromedriver>`_.
The browser makes its own requests for a page's images, scripts and other resources, so they aren't subject to the crawl
scope, robots.txt or the frontier's politeness delays. Responses are captured by a proxy server in Heritrix, passed
through the extractors in the fetch chain and then the disposition chain, which writes them to WARC. Links extracted
from them are scoped and queued as usual.
Enabling BrowserProcessor
~~~~~~~~~~~~~~~~~~~~~~~~~
Pages are loaded in the browser by ``BrowserProcessor``, which runs in the fetch chain after the link extractors. The
default profile includes it as a commented-out ``browser`` bean:
.. tab:: XML
.. code-block:: xml
<bean id="browser" class="org.archive.crawler.processor.BrowserProcessor">
<property name="behaviors">
<list>
<bean class="org.archive.modules.behaviors.ScrollDownBehavior" />
<bean class="org.archive.modules.behaviors.ExtractLinksBehavior" />
</list>
</property>
<property name="concurrency" value="20" />
<property name="executable" value="firefox" />
<property name="options">
<list>
<value>-headless</value>
</list>
</property>
</bean>
.. tab:: Groovy
.. code-block:: groovy
browser(BrowserProcessor) {
behaviors = [
new ScrollDownBehavior(),
new ExtractLinksBehavior()
]
concurrency = 20
executable = 'firefox'
options = ['-headless']
}
To enable it:
1. Uncomment the ``browser`` bean, and the reference to it at the end of the fetch chain.
2. Replace ``FetchHTTP`` with ``FetchHTTP2`` (see `HTTP/2`_). ``BrowserProcessor`` uses it to record the browser's
requests and for settings such as the user agent.
3. Install Firefox, or Chrome and a matching version of ChromeDriver.
``executable`` sets the browser to launch. If it isn't set, ``BrowserProcessor`` looks for ``firefox`` and then
``chromedriver``. ``options`` sets extra command-line arguments for the browser, by default ``--headless``.
Each page open in a browser occupies a toe thread until the browser is done with it, so set ``maxToeThreads`` to at
least the total ``concurrency`` of all browsers, plus some threads for fetching other URIs.
Configuring behaviors
~~~~~~~~~~~~~~~~~~~~~
After the page finishes loading, ``BrowserProcessor`` can run a set of behaviors.
- ``ExtractLinksBehavior`` finds links in the page and queues them. This differs from ``ExtractorHTML`` in that it can
see links that were dynamically added to the page by JavaScript.
- ``ScrollDownBehavior`` scrolls down to the bottom of the page so that lazy-loaded content loads.
- ``PaginationBehavior`` repeatedly clicks a "next page" button, found with the CSS selector set by ``selector``, and
extracts links after each click. Use it instead of ``ExtractLinksBehavior``.
Behaviors run in the order they're listed:
.. tab:: XML
.. code-block:: xml
<bean id="browser" class="org.archive.crawler.processor.BrowserProcessor">
<property name="behaviors">
<list>
<bean class="org.archive.modules.behaviors.ScrollDownBehavior" />
<bean class="org.archive.modules.behaviors.PaginationBehavior">
<property name="selector" value="a.next-page" />
</bean>
</list>
</property>
</bean>
.. tab:: Groovy
.. code-block:: groovy
browser(BrowserProcessor) {
behaviors = [
new ScrollDownBehavior(),
new PaginationBehavior(selector: 'a.next-page')
]
}
Running browsers on other machines
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As browsing is resource intensive, it can be helpful to spread the load across multiple servers.
``BrowserProcessor`` can be configured to launch browsers on remote machines using SSH.
To set up a remote machine:
1. Create a user for the browser to run as. It must have a POSIX-compatible shell (such as bash).
2. Install Firefox, or Chrome and a matching version of ChromeDriver, so it's on the ``PATH``.
On the machine Heritrix runs on:
1. Create an SSH key pair for the user Heritrix runs as:
.. code-block:: bash
ssh-keygen -t ed25519 -N ''
2. Copy the public key to ``~/.ssh/authorized_keys`` on the remote machine:
.. code-block:: bash
ssh-copy-id crawler@browser1.example.org
3. Connect once and accept the host key, then check that connecting works without any prompts:
.. code-block:: bash
ssh -o BatchMode=yes crawler@browser1.example.org firefox --version
Add the machine to the ``browsers`` list in the ``BrowserProcessor`` bean:
.. tab:: XML
.. code-block:: xml
<property name="browsers">
<list>
<value>local</value>
<value>ssh://crawler@browser1.example.org</value>
<bean class="org.archive.crawler.processor.SshBrowser">
<property name="uri" value="ssh://crawler@browser2.example.org" />
<property name="concurrency" value="40" />
<property name="executable" value="/opt/firefox/firefox" />
</bean>
</list>
</property>
.. tab:: Groovy
.. code-block:: groovy
browsers = [
'local',
'ssh://crawler@browser1.example.org',
new SshBrowser(uri: 'ssh://crawler@browser2.example.org', concurrency: 40,
executable: '/opt/firefox/firefox')
]
Monitoring the browsers
~~~~~~~~~~~~~~~~~~~~~~~
The ``BrowserProcessor`` entry in the processors report (``processors-report.txt``) shows how each browser is doing::
Processor: org.archive.crawler.processor.BrowserProcessor
Pages visited: 846
Subresources recorded: 24318
Browser 0: up, 3 open tabs, 312 pages visited, 0 restarts
Browser 1: idle, 0 open tabs, 297 pages visited, 2 restarts
Browser 2: down, 0 open tabs, 238 pages visited, 1 restarts, last failure: java.io.IOException: ssh did not report the port forwarded to the proxy
Behavior: org.archive.modules.behaviors.ScrollDownBehavior
Behavior: org.archive.modules.behaviors.ExtractLinksBehavior
Links extracted: 41275
A browser is *up* when it's running, and *idle* when it has been closed after ``browserIdleTimeoutSeconds`` with no
open pages. It's launched again when a page needs it, and is *waking* while it starts. A browser that failed to
launch or crashed is *down*, and is retried in the background.
Modifying a Running Job
-----------------------
@@ -43,6 +43,7 @@ import org.archive.modules.fetcher.FetchStatusCodes;
import org.archive.net.MitmProxy;
import org.archive.net.webdriver.*;
import org.archive.spring.KeyedProperties;
import org.archive.url.URIException;
import org.archive.util.IdleBarrier;
import org.archive.util.Recorder;
import org.eclipse.jetty.client.ProxyConfiguration;
@@ -106,6 +107,7 @@ public class BrowserProcessor extends Processor {
protected final CrawlController crawlController;
protected MitmProxy proxy;
protected final FetchHTTP2 fetcher;
protected final UriErrorLoggerModule uriErrorLoggerModule;
protected final List<Browser> pool = new CopyOnWriteArrayList<>();
protected ScheduledExecutorService launcher;
protected final Object tabsLock = new Object();
@@ -127,7 +129,8 @@ public class BrowserProcessor extends Processor {
this.crawlController = crawlController;
this.fetcher = fetcher;
this.eventPublisher = eventPublisher;
this.behaviors = List.of(new ScrollDownBehavior(), new ExtractLinksBehavior(uriErrorLoggerModule));
this.uriErrorLoggerModule = uriErrorLoggerModule;
this.behaviors = List.of(new ScrollDownBehavior(), new ExtractLinksBehavior());
}
public synchronized void stop() {
@@ -269,7 +272,7 @@ public class BrowserProcessor extends Processor {
String userAgent = curi.getUserAgent();
if (userAgent == null) userAgent = fetcher.getUserAgentProvider().getUserAgent();
BrowserPage page = new BrowserPage(curi, new IdleBarrier(), driver, tab, fetcher.getProxy(), userAgent,
new CompletableFuture<>());
new CompletableFuture<>(), uriErrorLoggerModule);
pages.put(pageId, page);
pageIdsByContext.put(tab, pageId);
driver.network().addIntercept(List.of(Network.InterceptPhase.beforeRequestSent), List.of(tab),
@@ -868,7 +871,8 @@ public class BrowserProcessor extends Processor {
BrowsingContext.Context context,
ProxyConfiguration.Proxy proxy,
String userAgent,
CompletableFuture<Void> downloadStarted
CompletableFuture<Void> downloadStarted,
UriErrorLoggerModule uriErrorLoggerModule
) implements Page {
/**
@@ -902,5 +906,10 @@ public class BrowserProcessor extends Processor {
public <T> T evalPromise(String script, Object... args) {
return callFunction(script, true, args);
}
@Override
public void logUriError(URIException e, String link) {
if (uriErrorLoggerModule != null) uriErrorLoggerModule.logUriError(e, curi.getUURI(), link);
}
}
}
@@ -15,10 +15,12 @@ import org.archive.crawler.frontier.*
import org.archive.crawler.monitor.DiskSpaceMonitor
import org.archive.crawler.postprocessor.*
import org.archive.crawler.prefetch.*
import org.archive.crawler.processor.*
import org.archive.crawler.reporting.*
import org.archive.crawler.spring.*
import org.archive.crawler.util.BdbUriUniqFilter
import org.archive.modules.*
import org.archive.modules.behaviors.*
import org.archive.modules.canonicalize.*
import org.archive.modules.deciderules.surt.SurtPrefixedDecideRule
import org.archive.modules.extractor.*
@@ -288,6 +290,22 @@ http://example.example/example
extractorCss(ExtractorCSS)
extractorJs(ExtractorJS)
extractorSwf(ExtractorSWF)
/*
browser(BrowserProcessor) {
behaviors = [
new ScrollDownBehavior(),
new ExtractLinksBehavior()
]
concurrency = 20
browsers = [
'local',
'ssh://crawler@browser1.example.org',
new SshBrowser(uri: 'ssh://crawler@browser2.example.org', concurrency: 40)
]
executable = 'firefox'
options = ['-headless']
}
*/
// now, processors are assembled into ordered FetchChain bean
fetchProcessors(FetchChain) {
processors = [
@@ -317,7 +335,9 @@ http://example.example/example
// ...extract outlinks from Javascript content...
ref('extractorJs'),
// ...extract outlinks from Flash content...
ref('extractorSwf')
ref('extractorSwf'),
// ...visit in a web browser...
// ref('browser')
]
}
@@ -86,7 +86,7 @@ class BrowserProcessorTest {
@Test
public void testPaginationBehavior() throws IOException, InterruptedException {
var defaultBehaviors = browserProcessor.getBehaviors();
browserProcessor.setBehaviors(List.of(new PaginationBehavior(null)));
browserProcessor.setBehaviors(List.of(new PaginationBehavior()));
try {
CrawlURI crawlURI = newCrawlURI(baseUrl + "paginated");
fetcher.process(crawlURI);
@@ -23,7 +23,6 @@ import org.archive.url.URIException;
import org.archive.modules.CrawlURI;
import org.archive.modules.extractor.Hop;
import org.archive.modules.extractor.LinkContext;
import org.archive.modules.extractor.UriErrorLoggerModule;
import org.archive.net.UURI;
import org.archive.net.UURIFactory;
@@ -35,11 +34,6 @@ import java.util.concurrent.atomic.AtomicLong;
*/
public class ExtractLinksBehavior implements Behavior {
private final AtomicLong numberOfLinksExtracted = new AtomicLong(0);
private final UriErrorLoggerModule loggerModule;
public ExtractLinksBehavior(UriErrorLoggerModule loggerModule) {
this.loggerModule = loggerModule;
}
public void run(Page page) {
List<String> urls = page.eval(/* language=JavaScript */ """
@@ -63,7 +57,7 @@ public class ExtractLinksBehavior implements Behavior {
page.curi().getOutLinks().add(link);
numberOfLinksExtracted.incrementAndGet();
} catch (URIException e) {
loggerModule.logUriError(e, page.curi().getUURI(), url);
page.logUriError(e, url);
}
}
}
@@ -20,6 +20,7 @@
package org.archive.modules.behaviors;
import org.archive.modules.CrawlURI;
import org.archive.url.URIException;
/**
* Represents a {@link CrawlURI} loaded as web page that a @{@link Behavior} can
@@ -31,4 +32,9 @@ public interface Page {
<T> T eval(String script, Object... args);
<T> T evalPromise(String script, Object... args);
/**
* Logs a link found on the page that couldn't be parsed.
*/
void logUriError(URIException e, String link);
}
@@ -19,8 +19,6 @@
package org.archive.modules.behaviors;
import org.archive.modules.extractor.UriErrorLoggerModule;
import java.util.concurrent.atomic.AtomicLong;
/**
@@ -28,16 +26,12 @@ import java.util.concurrent.atomic.AtomicLong;
* extracting links after each click. Use as a replacement for ExtractLinksBehavior.
*/
public class PaginationBehavior implements Behavior {
private final ExtractLinksBehavior extractLinks;
private final ExtractLinksBehavior extractLinks = new ExtractLinksBehavior();
private final AtomicLong pagesClicked = new AtomicLong();
private String selector = "button[title=\"Next\"]";
private int maxPages = 100;
private long loadTimeout = 5000;
public PaginationBehavior(UriErrorLoggerModule loggerModule) {
this.extractLinks = new ExtractLinksBehavior(loggerModule);
}
/**
* CSS selector for the next-page button.
*/