/crux

Crux offers a flexible plugin-based API & implementation to extract interesting information from Web pages.

Primary LanguageKotlinApache License 2.0Apache-2.0

Crux

Crux offers a flexible plugin-based API & implementation to extract interesting information from Web pages.

Sample Code

Kotlin

// Create a reusable object configured with the default set of plugins.
val crux = Crux()

val httpURL = "https://chimbori.com/".toHttpUrl()

// You can provide prefetched raw HTML content yourself, or have Crux fetch
// it for you.
val htmlContent = """
  |<html>
  |  <head>
  |    <title>Chimbori</title>
  |    <meta name="twitter:image" property="og:image"
  |        content="https://chimbori.com/media/cover-photo.png">
  |    <meta name="twitter:site" content="ChimboriApps">
  |    <link rel="apple-touch-icon-precomposed" sizes="192x192"
  |        href="https://chimbori.com/media/favicon.png">
  |  </head>
  |</html>
  |""".trimMargin()

// Crux runs inside a `suspend` function as a Kotlin Coroutine.
val extractedMetadata = runBlocking {
  crux.extractFrom(originalUrl = httpURL, parsedDoc = Jsoup.parse(htmlContent, httpURL.toString))
}

// Metadata fields such as the Title and Description are available from the
// returned [Resource] object as an indexed collection.
assertEquals("Chimbori", extractedMetadata[TITLE])

// Well-known URLs related to this page are available either as strings or
// OkHttp [HttpUrl]s.
assertEquals("https://chimbori.com/media/favicon.png", extractedMetadata[FAVICON_URL])
assertEquals("https://chimbori.com/media/favicon.png".toHttpUrl(),
    extractedMetadata.urls[FAVICON_URL])

// Extra markup fields like Twitter Cards metadata or Open Graph metadata are
// available as metadata fields as well.
assertEquals("https://chimbori.com/media/cover-photo.png", extractedMetadata[BANNER_IMAGE_URL])

Java

import com.chimbori.crux.Crux;
import com.chimbori.crux.api.Resource;
import kotlin.coroutines.Continuation;
import kotlin.coroutines.CoroutineContext;
import kotlin.coroutines.EmptyCoroutineContext;
import okhttp3.HttpUrl;
import java.util.concurrent.CompletableFuture;
// Other imports here...

// Create a reusable object configured with the default set of plugins.
var crux = Crux();

var httpURL = HttpUrl.get("https://chimbori.com/");

var htmlContent = """
  <html>
    <head>
      <title>Chimbori</title>
      <meta name="twitter:image" property="og:image"
          content="https://chimbori.com/media/cover-photo.png">
      <meta name="twitter:site" content="ChimboriApps">
      <link rel="apple-touch-icon-precomposed" sizes="192x192"
          href="https://chimbori.com/media/favicon.png">
    </head>
  </html>""";

// Scrape page text, if you please
final CompletableFuture<Resource> extractedMetadataFuture = new CompletableFuture<>();
crux.extractFrom(httpURL, Jsoup.parse(htmlContent, httpURL.toString()), new Continuation<Resource>() {
  @Override
  public CoroutineContext getContext() {
    return EmptyCoroutineContext.INSTANCE;
  }

  @Override
  public void resumeWith(Object value) {
    Resource extractedMetadata = (Resource) value;
    extractedMetadataFuture.complete(extractedMetadata);
  }
});

Resource extractedMetadata = extractedMetadataFuture.get();

// Metadata fields such as the Title and Description are available from the
// returned [Resource] object as an indexed collection.
assertEquals("Chimbori", extractedMetadata.get(Fields.TITLE).toString());

// Well-known URLs related to this page are available either as strings.
assertEquals("https://chimbori.com/media/favicon.png", extractedMetadata.get(Fields.FAVICON_URL).toString());

// Extra markup fields like Twitter Cards metadata or Open Graph metadata are
// available as metadata fields as well.
assertEquals("https://chimbori.com/media/cover-photo.png", extractedMetadata.get(Fields.BANNER_IMAGE_URL).toString())

Default Plugins

HtmlMetadataPlugin

Extracts titles, banner images, & other metadata from any web page.

  • Support for more metadata formats: OpenGraph, Twitter Cards, Schema.org.

ArticleExtractorPlugin

Strips out sidebars, navigation bars, and other unimportant parts of a page, and extracts the core article content.

  • Rich formatted content available, not just plain text.
  • Support for more sites & better parsing overall.
  • Small footprint and code size: JSoup & OkHttp are the only required dependencies.

Retaining specific nodes via crux-keep

If you control the HTML that is fed into Crux, and would like to instruct Crux to keep certain DOM nodes, irrespective of what Crux’s algorithm recommends, add the special attribute crux-keep to each such DOM node.

<p crux-keep="true">
  Content that should not be removed.
</p>

AmpPlugin

Rewrites the URL of an AMP page to its canonical (original) URL.

GoogleStaticRedirectorPlugin

Rewrites URLs generated by the Google Redirector Service to their canonical (original) URLs.

FacebookStaticRedirectorPlugin

Rewrites URLs generated by the Facebook Redirector Service to their canonical (original) URLs.

Optional Plugins

TrackingParameterRemover

Removes URL parameters typically used by analytics providers to track users’ behavior across the Web. This plugin is optional because it may break some misconfigured URLs and cause them to return the wrong content.

Design & Features

Crux is designed as a chain of plugins; each one performs a small specific task.

Each plugin receives as input a Resource object, which includes a URL and all the fields populated by previous plugins in the chain. Each plugin can

  • extract new pieces of metadata and add them to the output, or
  • overwrite existing fields by setting a new value for the same key, or
  • remove existing fields by setting a null value for that key.

A small set of well-known key names are defined in the API as Fields, but plugins and clients are not restricted to this set. You can extend Crux for your own applications by defining and using your own string keys for extracted metadata.

Plugins can rewrite URLs, which are then passed on down the chain. This is how HTTP redirects (301 and 302) as well as static redirectors (such as those from Google and Facebook) are handled.

Each plugin is independent of others. You can pick and choose the ones you want to use. If you use Crux in an Android app, Proguard or other minification tools can strip out the plugins you don’t use.

Crux’s API includes fewer setters/getters (compared to other such libraries), to keep the method count low (this is important for Android). Its plugin-based architecture makes it cleaner & leaner, compared to other libraries not explicitly optimized for Android.

Writing a Custom Plugin

// If you write a new plugin yourself, you can add any custom fields to the `Resource` object
// yourself, and consume them in your own app.
val customerNumberExtractorPlugin = object : Plugin {
  // Indicate that your plugin can handle all URLs on your site, but no others.
  override fun canHandle(url: HttpUrl): Boolean = url.topPrivateDomain() == "your-website.com"

  // Fields in the returned [Resource] overwrite those in the input [request]. If no changes are
  // to be made, then return null from your plugin. Otherwise, only return those fields that are
  // new or changed from the input.
  override suspend fun handle(request: Resource) = Resource(
      fields = mapOf(CUSTOMER_NUMBER_FIELD to request.url?.queryParameter("customer-number"))
  )

  val CUSTOMER_NUMBER_FIELD = "customer-number"
}

val cruxWithCustomPlugin = Crux(DEFAULT_PLUGINS + customerNumberExtractorPlugin)
val orderDetailsUrl = "https://www.your-website.com/orders?customer-number=42".toHttpUrl()

val metadata = runBlocking {
  cruxWithCustomPlugin.extractFrom(orderDetailsUrl, Document(orderDetailsUrl.toString()))
}
// Input URL was unchanged and is available in the output metadata.
assertEquals(orderDetailsUrl, metadata.url)
// Data extracted by the custom plugin is available as a custom field.
assertEquals("42", metadata[customerNumberExtractorPlugin.CUSTOMER_NUMBER_FIELD])

Image URL Extractor API

From a single DOM Element root, the Image URL API inspects the sub-tree and returns the best possible image URL candidate available within it. It does this by scanning within the DOM tree for interesting src & style tags.

All URLs are resolved as absolute URLs, even if the HTML contained relative URLs.

ImageUrlExtractor(url, domElement).findImage().imageUrl

Anchor Links Extractor API

From a single DOM Element root, the Image URL API inspects the sub-tree and returns the best possible link URL candidate available within it. It does this by scanning within the DOM tree for interesting href tags.

All URLs are resolved as absolute URLs, even if the HTML contained relative URLs.

LinkUrlExtractor(url, domElement).findLink().linkUrl

URL Heuristics API

This API examines a given URL (without connecting to the server), and returns heuristically-determined answers to questions such as:

  • Is this URL likely a video URL?
  • Is this URL likely an image URL?
  • Is this URL likely an audio URL?
  • Is this URL likely an executable URL?
  • Is this URL likely an archive URL?
val url = "https://example.com/article.html".toHttpUrl()

assertTrue(url.isLikelyArticle())
assertFalse(url.isLikelyImage())

Usage

Include Crux in your project, then see sample code for each API provided above.

Crux uses semantic versioning. If the API changes, then the major version will be incremented. Upgrading from one minor version to the next minor version within the same major version should not require any client code to be modified.

The latest release is available via Maven Central or GitHub Releases.

Maven Central

Get Crux via Maven

<dependency>
  <groupId>com.chimbori.crux</groupId>
  <artifactId>crux</artifactId>
  <version>0.0.0</version>   <!-- See the latest version number above. -->
</dependency>

Get Crux via Gradle

Gradle Groovy DSL

Project/build.gradle

allprojects {
  repositories {
    mavenCentral()
  }
}

Module/build.gradle:

dependencies {
  implementation 'com.chimbori.crux:crux:0.0.0'  // See the latest version number above.
}

Gradle Kotlin DSL

Project/build.gradle.kts

allprojects {
  repositories {
    mavenCentral()
  }
}

Module/build.gradle.kts:

dependencies {
  implementation("com.chimbori.crux:crux:0.0.0")  // See the latest version number above.
}

History

Crux began as a fork of Snacktory with the goal of making it more performant on Android devices, but it has quickly gained several new features that are not available in Snacktory.

Snacktory (and thus Crux) borrow ideas and test cases from Goose and JReadability.

License

Copyright 2016, Chimbori, makers of Hermit, the Lite Apps Browser.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.