Skip to content
/ crux Public

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

License

Notifications You must be signed in to change notification settings

chimbori/crux

Repository files navigation

Crux

Crux offers a flexible plugin-based API & implementation to extract metadata from Web pages. As of v5.0, Crux no longer extracts article information from web page text; read on for recommended alternatives.

Usage

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

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.
}

Sample Code

// 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])

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.

Default Plugins

HtmlMetadataPlugin

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

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

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.

Writing a Custom Plugin

ArticleExtractorPlugin

As of v5.0, Crux no longer contains its own article extraction plugin. We recommend dankito/Readability4J, a fork of Mozilla’s Readability.js, which is higher-quality and newer than Crux’s origin, Snacktory. We recommend that you use it instead of relying on Crux’s parser (which has now been removed).

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

build.gradle.kts:

dependencies {
  implementation("net.dankito.readability4j:readability4j:1.0.8")
}

Readability4JPlugin.kt:

import com.chimbori.crux.api.Extractor
import com.chimbori.crux.api.Fields.DURATION_MS
import com.chimbori.crux.api.Fields.TITLE
import com.chimbori.crux.api.Resource
import com.chimbori.crux.common.estimatedReadingTimeMs
import com.chimbori.crux.common.isLikelyArticle
import net.dankito.readability4j.extended.Readability4JExtended
import okhttp3.HttpUrl

class Readability4JPlugin : Extractor {
  override fun canExtract(url: HttpUrl) = url.isLikelyArticle()

  override suspend fun extract(request: Resource): Resource? = if (request.url != null && request.document != null) {
    val readability4J = Readability4JExtended(request.url.toString(), request.document!!)
    val article = readability4J.parse()
    Resource(
      article = article.articleContent,
      metadata = mapOf(
        TITLE to article.title,
        DURATION_MS to article.articleContent?.text()?.estimatedReadingTimeMs()
      ),
    )
  } else {
    null
  }
}

Then add Readability4JPlugin to the list of Crux plugins to use it along with Crux’s default plugins.

CustomerNumberExtractorPlugin

As an example, one can write a custom plugin to extract specific fields from a URL as follows:

// 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())

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.