Meeseeks v0.12.0 Meeseeks View Source

Meeseeks is an Elixir library for parsing and extracting data from HTML and XML with CSS or XPath selectors.

import Meeseeks.CSS

html = HTTPoison.get!("https://news.ycombinator.com/").body

for story <- Meeseeks.all(html, css("tr.athing")) do
  title = Meeseeks.one(story, css(".title a"))
  %{title: Meeseeks.text(title),
    url: Meeseeks.attr(title, "href")}
end
#=> [%{title: "...", url: "..."}, %{title: "...", url: "..."}, ...]

Features

  • Friendly API
  • Browser-grade HTML5 parser
  • Permissive XML parser
  • CSS and XPath selectors
  • Rich, extensible selector architecture
  • Helpers to extract data from selections

Why?

Meeseeks exists in the same space as an earlier library called Floki, so why was Meeseeks created and why would you use it instead of Floki?

Floki is a couple years older than Meeseeks, so why does Meeseeks even exist?

Meeseeks exists because Floki used to be unable to do what I needed.

When I started learning Elixir I reimplemented a small project I had written in another language. Part of that project involved extracting data from HTML, and unbeknownst to me some of the HTML I needed to extract data from was malformed.

This had never been a problem before because the HTML parser I was using in the other language was HTML5 spec compliant and handled the malformed HTML just as well as a browser. Unfortunately for me, Floki used (and still uses by default) the :mochiweb_html parser which is nowhere near HTML5 spec compliant, and just silently dropped the data I needed when parsing.

Meeseeks started out as an attempt to write an HTML5 spec compliant parser in Elixir (spoiler: it's really hard), then switched to using Mozilla's html5ever via Rustler after Hans wrote html5ever_elixir.

Floki gained optional support for using html5ever_elixir as its parser around the same time, but it still used :mochiweb_html (which doesn't require Rust to be part of the build process) by default and I released Meeseeks as a safer alternative.

Why should I use Meeseeks instead of Floki?

When Meeseeks was released it came with a safer default HTML parser, a more complete collection of CSS selectors, and a more extensible selector architecture than Floki.

Since then Meeseeks has been further expanded with functionality Floki just doesn't have, such as an XML parser and XPath selectors.

It won't matter to most users, but the selection architecture is much richer than Floki's, and permits the creation all kinds of interesting custom, stateful selectors (in fact, both the CSS and XPath selector strings compile down to the same selector structs that anybody can define).

What probably will matter more to users is the friendly API, extensive documentation, and the attention to the details of usability seen in such places as the custom formatting for result structs (#Meeseeks.Result<{ <p>1</p> }>) and the descriptive errors.

Is Floki ever a better choice than Meeseeks?

Yes, there are two main cases when Floki is clearly a better choice than Meeseeks.

Firstly, if you absolutely can't include Rust in your build process AND you know that the HTML you'll be working with is well-formed and won't require an HTML5 spec compliant parser then using Floki with the :mochiweb_html parser is a reasonable choice.

However, if you have any doubts about the HTML you'll be parsing you should probably figure out a way to use a better parser because using :mochiweb_html in that situation may be a timebomb.

Secondly, if you want to make updates to an HTML document then Floki provides facilities to do so while Meeseeks, which is entirely focused on selecting and extracting data, does not.

How does performance compare between Floki and Meeseeks?

Performance is similar enough between the two that it's probably not worth choosing one over the other for that reason.

For details and benchmarks, see Meeseeks vs. Floki Performance .

Compatibility

Meeseeks is tested with a minimum combination of Elixir 1.4.0 and Erlang/OTP 19.3, and a maximum combination of Elixir 1.8.1 and Erlang/OTP 21.0.

Dependencies

Meeseeks depends on html5ever via meeseeks_html5ever.

Because html5ever is a Rust library, you will need to have the Rust compiler installed.

This dependency is necessary because there are no HTML5 spec compliant parsers written in Elixir/Erlang.

Getting Started

Parse

Start by parsing a source (HTML/XML string or Meeseeks.TupleTree) into a Meeseeks.Document so that it can be queried.

Meeseeks.parse/1 parses the source as HTML, but Meeseeks.parse/2 accepts a second argument of either :html or :xml that specifies how the source is parsed.

document = Meeseeks.parse("<div id=main><p>1</p><p>2</p><p>3</p></div>")
#=> Meeseeks.Document<{...}>

The selection functions accept an unparsed source, parsing it as HTML, but parsing is expensive so parse ahead of time when running multiple selections on the same document.

Select

Next, use one of Meeseeks's selection functions - fetch_all, all, fetch_one, or one - to search for nodes.

All these functions accept a queryable (a source, a document, or a Meeseeks.Result), one or more Meeseeks.Selectors, and optionally an initial context.

all returns a (possibly empty) list of results representing every node matching one of the provided selectors, while one returns a result representing the first node to match a selector (depth-first) or nil if there is no match.

fetch_all and fetch_one work like all and one respectively, but wrap the result in {:ok, ...} if there is a match or return {:error, %Meeseeks.Error{type: :select, reason: :no_match}} if there is not.

To generate selectors, use the css macro provided by Meeseeks.CSS or the xpath macro provided by Meeseeks.XPath.

import Meeseeks.CSS
result = Meeseeks.one(document, css("#main p"))
#=> #Meeseeks.Result<{ <p>1</p> }>

import Meeseeks.XPath
result = Meeseeks.one(document, xpath("//*[@id='main']//p"))
#=> #Meeseeks.Result<{ <p>1</p> }>

Extract

Retrieve information from the Meeseeks.Result with an extraction function.

The extraction functions are attr, attrs, data, dataset, html, own_text, tag, text, tree.

Meeseeks.tag(result)
#=> "p"
Meeseeks.text(result)
#=> "1"
Meeseeks.tree(result)
#=> {"p", [], ["1"]}

The extraction functions html and tree work on Meeseeks.Documents in addition to Meeseeks.Results.

Meeseeks.html(document)
#=> "<html><head></head><body><div id=\"main\"><p>1</p><p>2</p><p>3</p></div></body></html>"

Custom Selectors

Meeseeks is designed to have extremely extensible selectors, and creating a custom selector is as easy as defining a struct that implements the Meeseeks.Selector behaviour.

defmodule CommentContainsSelector do
  use Meeseeks.Selector

  alias Meeseeks.Document

  defstruct value: ""

  def match(selector, %Document.Comment{} = node, _document, _context) do
    String.contains?(node.content, selector.value)
  end

  def match(_selector, _node, _document, _context) do
    false
  end
end

selector = %CommentContainsSelector{value: "TODO"}

Meeseeks.one("<!-- TODO: Close vuln! -->", selector)
#=> #Meeseeks.Result<{ <!-- TODO: Close vuln! --> }>

To learn more, check the documentation for Meeseeks.Selector and Meeseeks.Selector.Combinator

Link to this section Summary

Functions

Returns [Result, ...] if one or more nodes in the queryable match a selector, or [] if none do

Returns the value of an attribute in a result, or nil if there isn't one

Returns a result's attributes list, which may be empty, or nil if the result represents a node without attributes

Returns the combined data of a result or the result's children, which may be an empty string

Returns a map of a result's data attributes, or nil if the result represents a node without attributes

Returns {:ok, [Result, ...]} if one of more nodes in the queryable match a selector, or {:error, %Meeseeks.Error{type: :select, reason: :no_match}} if none do

Returns {:ok, Result} for the first node in the queryable (depth-first) matching a selector, or {:error, %Meeseeks.Error{type: :select, reason: :no_match}} if none do

Returns a string representing the combined HTML of a document or result and its descendants

Returns a Result for the first node in the queryable (depth-first) matching a selector, or nil if none do

Returns the combined text of a result or the result's children, which may be an empty string

Returns the accumulated result of walking the queryable, accumulating nodes that match a selector. Prefer all or one- select should only be used when a custom accumulator is required

Returns a result's tag, or nil if the result represents a node without a tag

Returns the combined text of a result or the result's descendants, which may be an empty string

Returns the Meeseeks.TupleTree of a document or result and its descendants

Link to this section Types

Link to this type

queryable() View Source
queryable() ::
  Meeseeks.Parser.source() | Meeseeks.Document.t() | Meeseeks.Result.t()

Link to this section Functions

Link to this function

all(queryable, selectors) View Source
all(queryable(), selectors()) ::
  [Meeseeks.Result.t()] | {:error, Meeseeks.Error.t()}

Returns [Result, ...] if one or more nodes in the queryable match a selector, or [] if none do.

Optionally accepts a Meeseeks.Context map.

Parses the source if it is not a Meeseeks.Document or Meeseeks.Result, and may return {:error, %Meeseeks.Error{type: parser} if there is a parse error.

If multiple selections are being ran on the same unparsed source, parse first to avoid unnecessary computation.

Examples

iex> import Meeseeks.CSS
iex> Meeseeks.all("<div id=main><p>1</p><p>2</p><p>3</p></div>", css("#main p")) |> List.first()
#Meeseeks.Result<{ <p>1</p> }>
Link to this function

all(queryable, selectors, context) View Source

Link to this function

attr(extractable, attribute) View Source
attr(extractable(), String.t()) :: String.t() | nil

Returns the value of an attribute in a result, or nil if there isn't one.

Nil input returns nil.

Examples

iex> import Meeseeks.CSS
iex> result = Meeseeks.one("<div id=example>Hi</div>", css("#example"))
#Meeseeks.Result<{ <div id="example">Hi</div> }>
iex> Meeseeks.attr(result, "id")
"example"
Link to this function

attrs(extractable) View Source
attrs(extractable()) :: [{String.t(), String.t()}] | nil

Returns a result's attributes list, which may be empty, or nil if the result represents a node without attributes.

Nil input returns nil.

Examples

iex> import Meeseeks.CSS
iex> result = Meeseeks.one("<div id=example>Hi</div>", css("#example"))
#Meeseeks.Result<{ <div id="example">Hi</div> }>
iex> Meeseeks.attrs(result)
[{"id", "example"}]
Link to this function

data(extractable) View Source
data(extractable()) :: String.t() | nil

Returns the combined data of a result or the result's children, which may be an empty string.

Data is the content of <script> or <style> tags, or the content of comments starting with "[CDATA[" and ending with "]]". The latter behavior is to support the extraction of CDATA from HTML, since HTML5 parsers parse CDATA as comments.

Nil input returns nil.

Examples

iex> import Meeseeks.CSS
iex> result1 = Meeseeks.one("<div id=example>Hi</div>", css("#example"))
#Meeseeks.Result<{ <div id="example">Hi</div> }>
iex> Meeseeks.data(result1)
""
iex> result2 = Meeseeks.one("<script id=example>Hi</script>", css("#example"))
#Meeseeks.Result<{ <script id="example">Hi</script> }>
iex> Meeseeks.data(result2)
"Hi"
Link to this function

dataset(extractable) View Source
dataset(extractable()) :: %{optional(String.t()) => String.t()} | nil

Returns a map of a result's data attributes, or nil if the result represents a node without attributes.

Behaves like HTMLElement.dataset; only valid data attributes are included, and attribute names have "data-" removed and are converted to camelCase.

See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

Nil input returns nil.

Examples

iex> import Meeseeks.CSS
iex> result = Meeseeks.one("<div id=example data-x-val=1 data-y-val=2></div>", css("#example"))
#Meeseeks.Result<{ <div id="example" data-x-val="1" data-y-val="2"></div> }>
iex> Meeseeks.dataset(result)
%{"xVal" => "1", "yVal" => "2"}
Link to this function

fetch_all(queryable, selectors) View Source
fetch_all(queryable(), selectors()) ::
  {:ok, [Meeseeks.Result.t()]} | {:error, Meeseeks.Error.t()}

Returns {:ok, [Result, ...]} if one of more nodes in the queryable match a selector, or {:error, %Meeseeks.Error{type: :select, reason: :no_match}} if none do.

Optionally accepts a Meeseeks.Context map.

Parses the source if it is not a Meeseeks.Document or Meeseeks.Result, and may return {:error, %Meeseeks.Error{type: parser} if there is a parse error.

If multiple selections are being ran on the same unparsed source, parse first to avoid unnecessary computation.

Examples

iex> import Meeseeks.CSS
iex> Meeseeks.fetch_all("<div id=main><p>1</p><p>2</p><p>3</p></div>", css("#main p")) |> elem(1) |> List.first()
#Meeseeks.Result<{ <p>1</p> }>
Link to this function

fetch_all(queryable, selectors, context) View Source
fetch_all(queryable(), selectors(), Meeseeks.Context.t()) ::
  {:ok, [Meeseeks.Result.t()]} | {:error, Meeseeks.Error.t()}

Link to this function

fetch_one(queryable, selectors) View Source
fetch_one(queryable(), selectors()) ::
  {:ok, Meeseeks.Result.t()} | {:error, Meeseeks.Error.t()}

Returns {:ok, Result} for the first node in the queryable (depth-first) matching a selector, or {:error, %Meeseeks.Error{type: :select, reason: :no_match}} if none do.

Optionally accepts a Meeseeks.Context map.

Parses the source if it is not a Meeseeks.Document or Meeseeks.Result, and may return {:error, %Meeseeks.Error{type: parser} if there is a parse error.

If multiple selections are being ran on the same unparsed source, parse first to avoid unnecessary computation.

Examples

iex> import Meeseeks.CSS
iex> Meeseeks.fetch_one("<div id=main><p>1</p><p>2</p><p>3</p></div>", css("#main p")) |> elem(1)
#Meeseeks.Result<{ <p>1</p> }>
Link to this function

fetch_one(queryable, selectors, context) View Source
fetch_one(queryable(), selectors(), Meeseeks.Context.t()) ::
  {:ok, Meeseeks.Result.t()} | {:error, Meeseeks.Error.t()}

Link to this function

html(extractable) View Source
html(extractable()) :: String.t() | nil

Returns a string representing the combined HTML of a document or result and its descendants.

Nil input returns nil.

Examples

iex> import Meeseeks.CSS
iex> document = Meeseeks.parse("<div id=example>Hi</div>")
iex> Meeseeks.html(document)
"<html><head></head><body><div id=\"example\">Hi</div></body></html>"
iex> result = Meeseeks.one(document, css("#example"))
#Meeseeks.Result<{ <div id="example">Hi</div> }>
iex> Meeseeks.html(result)
"<div id=\"example\">Hi</div>"
Link to this function

one(queryable, selectors) View Source
one(queryable(), selectors()) ::
  Meeseeks.Result.t() | nil | {:error, Meeseeks.Error.t()}

Returns a Result for the first node in the queryable (depth-first) matching a selector, or nil if none do.

Optionally accepts a Meeseeks.Context map.

Parses the source if it is not a Meeseeks.Document or Meeseeks.Result, and may return {:error, %Meeseeks.Error{type: parser} if there is a parse error.

If multiple selections are being ran on the same unparsed source, parse first to avoid unnecessary computation.

Examples

iex> import Meeseeks.CSS
iex> Meeseeks.one("<div id=main><p>1</p><p>2</p><p>3</p></div>", css("#main p"))
#Meeseeks.Result<{ <p>1</p> }>
Link to this function

one(queryable, selectors, context) View Source

Link to this function

own_text(extractable) View Source
own_text(extractable()) :: String.t() | nil

Returns the combined text of a result or the result's children, which may be an empty string.

Nil input returns nil.

Examples

iex> import Meeseeks.CSS
iex> result = Meeseeks.one("<div>Hello, <b>World!</b></div>", css("div"))
#Meeseeks.Result<{ <div>Hello, <b>World!</b></div> }>
iex> Meeseeks.own_text(result)
"Hello,"
Link to this function

parse(source) View Source
parse(Meeseeks.Parser.source()) ::
  Meeseeks.Document.t() | {:error, Meeseeks.Error.t()}

Parses a string or Meeseeks.TupleTree into a Meeseeks.Document.

parse/1 parses as HTML, while parse/2 accepts a second argument of either :html, :xml, or tuple_tree that specifies how the source is parsed.

Examples

iex> Meeseeks.parse("<div id=main><p>Hello, Meeseeks!</p></div>")
#Meeseeks.Document<{...}>

iex> Meeseeks.parse("<book><author>GGK</author></book>", :xml)
#Meeseeks.Document<{...}>

iex> Meeseeks.parse({"div", [{"id", "main"}], [{"p", [], ["Hello, Meeseeks!"]}]}, :tuple_tree)
#Meeseeks.Document<{...}>
Link to this function

parse(source, parser) View Source
parse(Meeseeks.Parser.source(), Meeseeks.Parser.type()) ::
  Meeseeks.Document.t() | {:error, Meeseeks.Error.t()}

Link to this function

select(queryable, selectors, context) View Source
select(queryable(), selectors(), Meeseeks.Context.t()) ::
  any() | {:error, Meeseeks.Error.t()}

Returns the accumulated result of walking the queryable, accumulating nodes that match a selector. Prefer all or one- select should only be used when a custom accumulator is required.

Requires that a Meeseeks.Accumulator has been added to the context via Meeseeks.Context.add_accumulator/2, and will raise an error if it hasn't.

Parses the source if it is not a Meeseeks.Document or Meeseeks.Result, and may return {:error, %Meeseeks.Error{type: parser} if there is a parse error.

If multiple selections are being ran on the same unparsed source, parse first to avoid unnecessary computation.

Examples

iex> import Meeseeks.CSS
iex> accumulator = %Meeseeks.Accumulator.One{}
iex> context = Meeseeks.Context.add_accumulator(%{}, accumulator)
iex> Meeseeks.select("<div id=main><p>1</p><p>2</p><p>3</p></div>", css("#main p"), context)
#Meeseeks.Result<{ <p>1</p> }>

Returns a result's tag, or nil if the result represents a node without a tag.

Nil input returns nil.

Examples

iex> import Meeseeks.CSS
iex> result = Meeseeks.one("<div id=example>Hi</div>", css("#example"))
#Meeseeks.Result<{ <div id="example">Hi</div> }>
iex> Meeseeks.tag(result)
"div"
Link to this function

text(extractable) View Source
text(extractable()) :: String.t() | nil

Returns the combined text of a result or the result's descendants, which may be an empty string.

Nil input returns nil.

Examples

iex> import Meeseeks.CSS
iex> result = Meeseeks.one("<div>Hello, <b>World!</b></div>", css("div"))
#Meeseeks.Result<{ <div>Hello, <b>World!</b></div> }>
iex> Meeseeks.text(result)
"Hello, World!"

Returns the Meeseeks.TupleTree of a document or result and its descendants.

Nil input returns nil.

Examples

iex> import Meeseeks.CSS
iex> document = Meeseeks.parse("<div id=example>Hi</div>")
iex> Meeseeks.tree(document)
[{"html", [],
  [{"head", [], []},
   {"body", [], [{"div", [{"id", "example"}], ["Hi"]}]}]}]
iex> result = Meeseeks.one(document, css("#example"))
#Meeseeks.Result<{ <div id="example">Hi</div> }>
iex> Meeseeks.tree(result)
{"div", [{"id", "example"}], ["Hi"]}