### Usage example for tags and tag Source: https://github.com/aantron/lambdasoup Shows how to use `tags` to iterate over all `a` elements and `tag` to get the first `nav` element. The example prints the `href` attribute for each link and the string representation of the nav element. ```ocaml soup |> tags "a" |> iter (fun a -> print_endline (R.attribute "href" a)); soup |> tag "nav" |> Option.iter (fun nav -> print_endline (to_string nav)) ``` -------------------------------- ### Set up OCaml environment for interactive use Source: https://github.com/aantron/lambdasoup/blob/master/README.md Commands to install OCaml and opam, initialize opam, set the environment, and install Lambda Soup, as needed for interactive use. ```sh your-package-manager install ocaml opam opam init eval `opam config env` # Or restart your shell opam install lambdasoup ``` -------------------------------- ### Install Lambda Soup via opam Source: https://github.com/aantron/lambdasoup/blob/master/README.md Command to install the Lambda Soup package using the opam package manager. ```sh opam install lambdasoup ``` -------------------------------- ### Full content extraction example Source: https://github.com/aantron/lambdasoup Example showing how to extract all text content from a div using texts, trimmed_texts, and leaf_text. The output shows the resulting string lists and option value. ```ocaml open Soup let soup = parse "

Title

Hello world!

" in texts (soup $ "div") (* - : string list = ["Title"; "Hello "; "world"; "!"] *) trimmed_texts (soup $ "div") (* - : string list = ["Title"; "Hello"; "world"; "!"] *) soup $ "p" |> leaf_text (* - : string option = Some "Hello world!" *) ``` -------------------------------- ### Example: flattening and one-step navigation Source: https://github.com/aantron/lambdasoup Demonstrates using next_sibling, previous_sibling, and parent on a parsed list. The output shows the expected option values for each operation. ```ocaml open Soup let soup = parse "" in let li = soup $ "#a" in next_sibling li |> Option.bind element |> Option.map name (* - : string option = Some "li" *) previous_sibling (soup $ "#b") |> Option.bind element |> Option.bind (fun e -> id e) (* - : string option = Some "a" *) parent li |> Option.map name (* the ul element *) (* - : string option = Some "ul" *) ``` -------------------------------- ### Positional queries example Source: https://github.com/aantron/lambdasoup Example showing `nth`, `count`, `index_of`, and `index_of_element` on a parsed list. `nth` is 1-based; `count` returns the number of matching nodes; both index functions return 1-based positions. ```ocaml open Soup let soup = parse "" in let second = soup $$ "li" |> nth 2 |> Option.get in R.attribute "class" second (* - : string = "b" *) soup $$ "li" |> count (* - : int = 3 *) index_of second (* 2 — position among all children *) index_of_element second (* 2 — same here, since all children are elements *) ``` -------------------------------- ### Example: rewriting a document Source: https://github.com/aantron/lambdasoup OCaml example that reads a document from stdin, parses it, iterates over all `a` tags, and for each with `href` equal to "old", sets the href to "new" and adds the class "migrated". Finally, the modified soup is written to stdout. This is the style of Lambda Soup's own docs postprocessor. ```ocaml open Soup let soup = read_channel stdin |> parse in soup |> tags "a" |> iter (fun a -> match attribute "href" a with | Some "old" -> set_attribute "href" "new" a; add_class "migrated" a | _ -> ()); soup |> to_string |> write_channel stdout ``` -------------------------------- ### Building a document from scratch Source: https://github.com/aantron/lambdasoup Example showing how to create a soup document, add an element with attributes, classes, and inner text, then append it as a root. The output shows the resulting HTML string with class and href attributes. ```ocaml open Soup let doc = create_soup () in let link = create_element "a" ~attributes:["href", "https://example.com"] ~classes:["btn"; "primary"] ~inner_text:"Click me" in append_root doc link; to_string doc (* - : string = "Click me" *) ``` -------------------------------- ### Example — combining the accessors Source: https://github.com/aantron/lambdasoup Parses an HTML snippet and uses `name`, `classes`, `id`, and `has_attribute` to inspect an element. The expected result is shown in the comment. ```ocaml open Soup let soup = parse "Go" in let a = soup $ "a" in (name a, classes a, id a, has_attribute "href" a) (* - : string * string list * string option * bool = ("a", ["btn"; "primary"], Some "go", true) *) ``` -------------------------------- ### Example: Walk the tree with children, ancestors, previous_siblings Source: https://github.com/aantron/lambdasoup Demonstrates using children, ancestors, and previous_siblings on a parsed soup. Shows that ancestors returns an empty list for a section because the soup node is not an element, and previous_siblings returns the div element. ```ocaml open Soup let soup = parse "

a

b

c
" in let p = soup $ "p" in children (soup $ "div") |> to_list |> List.map (fun n -> match element n with Some e -> name e | None -> "#text") (* - : string list = ["p"; "p"] *) ancestors (soup $ "section") |> to_list |> List.map name (* - : string list = [] — soup node is not an element, so no element ancestors *) soup $ "section" |> previous_siblings |> elements |> to_list |> List.map name (* - : string list = ["div"] *) ``` -------------------------------- ### Parse and extract text with CSS selector Source: https://github.com/aantron/lambdasoup/blob/master/README.md Shows a trivial self-contained example of parsing HTML and using the CSS selector '.Hello' to extract the leaf text, returning 'World!'. ```ocaml (parse "

World!

") $ ".Hello" |> R.leaf_text;; - : string = "World!" ``` -------------------------------- ### OCaml Soup replace/wrap/unwrap example Source: https://github.com/aantron/lambdasoup Shows usage of wrap and unwrap. The first part wraps a child element in a strong tag and outputs the modified HTML. The second part unwraps all i elements and outputs the result. ```ocaml open Soup let soup = parse "

World!

" in wrap (soup $ ".Hello" |> R.child) (create_element "strong"); to_string soup (* - : string = "

World!

" *) let s2 = parse "
ab
" in s2 $$ "i" |> iter unwrap; to_string s2 (* - : string = "
ab
" *) ``` -------------------------------- ### Error handling: $ raises Failure, $? returns None Source: https://github.com/aantron/lambdasoup Illustrates the difference in error handling: $ raises Failure with a message including a hint to use $?, while $? returns None. The example shows the exact failure message and the output 'missing' for the None case. ```ocaml let soup = Soup.parse "

no lists here

" in (try ignore (soup $ "footer") with Failure message -> print_endline message) (* Soup.($): 'footer' not found. Try Soup.($?) if you'd prefer returning None instead of an exception. *) match soup $? "footer" with | Some _ -> print_endline "found" | None -> print_endline "missing" (* missing *) ``` -------------------------------- ### Equality usage example Source: https://github.com/aantron/lambdasoup Shows equality checks with parse and create_element. equal is whitespace-sensitive, equal_modulo_whitespace ignores surrounding whitespace, and attribute order does not matter. ```ocaml open Soup equal (parse "

a

") (parse "

a

") (* true *) equal (parse "

a

") (parse "

b

") (* false *) equal_modulo_whitespace (parse "

a

") (parse "

b

") (* true *) let e = create_element "p" ~attributes:["b", "2"; "a", "1"] in equal e (create_element "p" ~attributes:["a", "1"; "b", "2"]) (* true: order-insensitive *) ``` -------------------------------- ### Example — iterating over attributes (and exercising coerce/element) Source: https://github.com/aantron/lambdasoup Uses `fold_attributes` to print each attribute name and value, then counts elements via `descendants`, `elements`, and `count`. ```ocaml soup $ "a" |> fold_attributes (fun acc name value -> (name, value) :: acc) [] |> List.iter (fun (n, v) -> Printf.printf "%s=%s\n" n v); soup |> descendants |> elements |> count |> Printf.printf "elements: %d\n" ``` -------------------------------- ### Example: descendants with early exit using with_stop Source: https://github.com/aantron/lambdasoup Shows how to combine descendants with early termination using with_stop to find the first span element. Returns None if no span is found. ```ocaml let first_span = with_stop (fun stop -> soup |> descendants |> elements |> iter (fun e -> if name e = "span" then stop.throw (Some e)); None) ``` -------------------------------- ### Optional argument precedence example Source: https://github.com/aantron/lambdasoup Demonstrates that ~class_ overrides ~classes and ~attributes, and ~id overrides ~attributes. The comment shows the resulting class and id values. ```ocaml create_element "p" ~attributes:["class", "a"; "id", "x"] ~classes:["b"; "c"] ~class_:"d" ~id:"y" (* class = "d" (class_ wins over classes and attributes); id = "y" (id wins over attributes) *) ``` -------------------------------- ### Example: is_root distinction between parse output and created nodes Source: https://github.com/aantron/lambdasoup Shows how is_root behaves differently for parsed documents, elements within a parsed document, and created elements. A parsed document is not a root, an element inside it is, and a created element with no parent is also a root. ```ocaml let parsed = parse "

x

" in is_root parsed (* false — it is a document node *) parsed $ "p" |> is_root (* true — its parent is the soup node *) create_element "p" |> is_root (* true — no parent at all *) ``` -------------------------------- ### from_signals to load XML Source: https://github.com/aantron/lambdasoup Builds a Lambda Soup document from a Markup.ml signal stream, enabling XML parsing (Lambda Soup proper only parses HTML) or non-string input. The example chains `Markup.string`, `Markup.parse_xml`, and `Markup.signals` before `from_signals`. ```ocaml Markup.string s |> Markup.parse_xml |> Markup.signals |> from_signals ``` -------------------------------- ### Combinator pipeline example Source: https://github.com/aantron/lambdasoup Shows a pipeline using filter, to_list, List.map, List.rev, and flatten. The first pipeline extracts href attributes from 'a' elements and reverses them, yielding ["2"; "1"]. The second uses flatten to concatenate descendant elements of each 'a' element. ```ocaml open Soup let soup = parse "x

y

z" in soup |> descendants |> elements |> filter (fun e -> name e = "a") |> to_list |> List.map (fun e -> R.attribute "href" e) |> List.rev (* - : string list = ["2"; "1"] *) soup $$ "a" |> flatten (fun a -> a |> descendants |> elements) |> count ``` -------------------------------- ### leaf_text examples Source: https://github.com/aantron/lambdasoup Examples from src/soup.mli:287-303 showing leaf_text behavior on various parsed HTML snippets. The first line shows the result for a simple text node, and the comments show results for nested elements. ```ocaml leaf_text (parse "some text") (* Some "some text" — soup node, one text root *) (*

some text

=> Some "some text" *) (*

x

=> Some "some text" *) (*

a

b

=> None *) (*
=> Some "" *) ``` -------------------------------- ### children: Get all child nodes Source: https://github.com/aantron/lambdasoup Returns the sequence of all children of a node in document order. Empty for text nodes. ```ocaml val children : (_ node) -> general nodes (* src/soup.mli:307 *) ``` -------------------------------- ### last/count force evaluation example Source: https://github.com/aantron/lambdasoup Illustrates that `count` forces the entire traversal, similar to `to_list`. This matters for cost, not semantics. ```ocaml let all = soup $$ "a[href]" |> to_list in (* forces the traversal *) let n = soup $$ "a[href]" |> count in (* also forces it *) ``` -------------------------------- ### Early termination example: find first draggable element Source: https://github.com/aantron/lambdasoup Uses with_stop to find the first element with a draggable attribute without walking the rest of the document. The stop.throw call returns Some element immediately, otherwise None is returned. ```ocaml with_stop (fun stop -> some_root_node |> descendants |> elements |> iter (fun element -> if has_attribute "draggable" element then stop.throw (Some element)); None) (* - : element node option = Some ... *) ``` -------------------------------- ### Qualified legacy usage with error handling Source: https://github.com/aantron/lambdasoup Demonstrates using `Lambdasoup.parse` and `Lambdasoup.select_one` with qualified names. The example prints "missing" because the selector does not match. ```ocaml let soup = Lambdasoup.parse "" in (match Lambdasoup.select_one "a[href='/2']" soup with | Some _ -> print_endline "found" | None -> print_endline "missing"); (* missing *) ``` -------------------------------- ### name Source: https://github.com/aantron/lambdasoup Returns the element's tag name, lowercased. For example, an `` element has tag name `a`. ```APIDOC ## name ### Description Returns the element's tag name, lowercased. For example, an `` element has tag name `a`. ### Signature ```ocaml val name : element node -> string ``` ### Parameters - **element** (`element node`) - Required - The element ### Returns `string` ``` -------------------------------- ### Basic scraping pipeline with Soup.R (OCaml) Source: https://github.com/aantron/lambdasoup Shows how to use Soup.R functions like R.leaf_text, R.nth, R.id, R.select_one, and R.attribute to avoid Option plumbing. The examples parse HTML and extract text or attributes, with expected outputs shown as comments. ```ocaml open Soup let soup = parse "

World!

" in soup $ ".Hello" |> R.leaf_text (* - : string = "World!" *) let soup = parse "" in soup $$ "li" |> R.nth 2 |> R.id (* - : string = "two" *) soup |> R.select_one "li.odd" |> R.attribute "class" (* - : string = "odd" *) ``` -------------------------------- ### filter_map with to_list example Source: https://github.com/aantron/lambdasoup Shows extracting string data by filtering first and using List.map after to_list. The comment notes that filter_map is node-to-node; for string results, filter first and use List.map after to_list. ```ocaml soup |> descendants |> elements |> filter (fun e -> name e = "img") |> to_list |> List.map (fun e -> R.attribute "src" e) (* - : string list = [...] — all image srcs, in document order *) ``` -------------------------------- ### Error handling with Soup.R and $ (OCaml) Source: https://github.com/aantron/lambdasoup Demonstrates catching the Failure raised by Soup.R functions and the $ operator when an element is not found. The first example prints 'Soup.R.select_one: None'; the second shows the $ operator's error message and suggests $? for returning None instead. ```ocaml open Soup let soup = parse "

no lists here

" in (try soup |> R.select_one "li" |> ignore with Failure message -> print_endline message) (* Soup.R.select_one: None *) (* The $ operator is the same composition for select_one: *) (try soup $ "li" |> ignore with Failure message -> print_endline message) (* Soup.($): 'li' not found. Try Soup.($?) if you'd prefer returning None instead of an exception. *) ``` -------------------------------- ### Early-exit fold example: find element at index 3 Source: https://github.com/aantron/lambdasoup Mimics 'find element at index 3' without materializing the sequence. Uses fold with a counter and stop.throw when the index matches. The result is ignored and None is returned if not found. ```ocaml with_stop (fun stop -> soup |> descendants |> elements |> fold (fun i e -> if i = 3 then stop.throw (Some e) else i + 1) 1 |> ignore; None) ``` -------------------------------- ### to_string and pretty_print usage Source: https://github.com/aantron/lambdasoup Converts a parsed node tree to an HTML5 string. `to_string` preserves whitespace; `pretty_print` formats for human reading but may change whitespace structure, affecting browser rendering. The example shows parsing a simple HTML snippet and printing both outputs. ```ocaml open Soup let soup = parse "

Hello

" in to_string soup (* - : string = "

Hello

" *) let formatted = pretty_print soup in print_endline formatted (* human-readable HTML; whitespace around nodes may differ from the input *) ``` -------------------------------- ### Catching Failure exceptions from Soup.R.select_one and Soup.replace Source: https://github.com/aantron/lambdasoup Shows how to catch `Failure _` exceptions raised by `Soup.R.select_one` and `Soup.replace`. The first example uses `$?` to avoid an exception and then catches the `Failure` from `Soup.R.select_one`, printing `Soup.R.select_one: None`. The second catches `Failure` from `Soup.replace` on an unattached node, printing `Soup.replace: target node has no parent`. ```ocaml let soup = parse "

" in match soup $? "span" with | Some _ -> () | None -> (try ignore (Soup.R.select_one "span" soup) with Failure message -> print_endline message) (* Soup.R.select_one: None *) try Soup.replace (create_element "p") (create_element "div") with | Failure message -> print_endline message (* Soup.replace: target node has no parent *) ``` -------------------------------- ### I/O helper signatures (read_file, read_channel, write_file, write_channel) Source: https://github.com/aantron/lambdasoup Thin wrappers over Pervasives/Markup.ml for quick scripts. read_file raises Sys_error on failure; write_file truncates existing files; write_channel uses output_string and may require flush. ```ocaml val read_file : string -> string (* src/soup.mli:695 *) val read_channel : in_channel -> string (* src/soup.mli:699 *) val write_file : string -> string -> unit (* src/soup.mli:702 *) val write_channel : out_channel -> string -> unit (* src/soup.mli:710 *) ``` -------------------------------- ### $ Source: https://github.com/aantron/lambdasoup Infix (pipeline-friendly) spelling of select_one post-composed with require. Raises Failure if nothing matched. ```APIDOC ## $ ### Description Infix (pipeline-friendly) spelling of select_one post-composed with require. Raises Failure if nothing matched. ### Method Infix Operator ### Signature ```ocaml val ($) : (_ node) -> string -> element node ``` ### Parameters - **node** (`(_ node)`) - Required - Root of the search; any node kind - **selector** (string) - Required - CSS selector; see grammar below ### Returns - `element node` — `select_one` post-composed with `require` ### Throws - `Parse_error of string` for syntactically invalid selectors - `Failure` when no match is found (message `Soup.($): '' not found.` + hint) ### Example ```ocaml open Soup let soup = read_channel stdin |> parse in let title = soup $ "title" |> R.leaf_text in (* first match, else Failure *) ``` ``` -------------------------------- ### Configure ~/.ocamlinit for top-level Source: https://github.com/aantron/lambdasoup/blob/master/README.md OCaml code to add to ~/.ocamlinit to enable findlib and topfind, required for using Lambda Soup interactively. ```ocaml let () = try Topdirs.dir_directory (Sys.getenv "OCAML_TOPLEVEL_PATH") with Not_found -> () ;; #use "topfind";; ``` -------------------------------- ### siblings: Get all siblings excluding self Source: https://github.com/aantron/lambdasoup Returns all siblings of a node in child-list order, excluding the node itself. Empty if the node has no parent. ```ocaml val siblings : (_ node) -> general nodes (* src/soup.mli:322 *) ``` -------------------------------- ### Error handling for invalid selectors Source: https://github.com/aantron/lambdasoup Catches Parse_error when a selector is syntactically invalid. Example message: "unterminated attribute selector". ```ocaml try soup |> select "[id=unterminated" |> ignore with | Soup.Parse_error message -> print_endline message (* e.g. "unterminated attribute selector" (src/soup.ml:824, 831, 841) *) ``` -------------------------------- ### descendants: Get all descendant nodes depth-first Source: https://github.com/aantron/lambdasoup Returns all descendants of a node, depth-first, in document order. The node itself is not included; empty for text nodes. ```ocaml val descendants : (_ node) -> general nodes (* src/soup.mli:311 *) ``` -------------------------------- ### Scraping patterns with select, $$, $ Source: https://github.com/aantron/lambdasoup Shows how to extract a title, all links with href, and an optional first list item. $ raises Failure if no match; $$ returns all matches; $? returns an option. ```ocaml open Soup let soup = read_channel stdin |> parse in let title = soup $ "title" |> R.leaf_text in (* first match, else Failure *) let links = soup $$ "a[href]" |> to_list in (* all links with href *) let first_li = soup $? "ul li" in (* option *) ``` -------------------------------- ### ancestors: Get element ancestors ordered by proximity Source: https://github.com/aantron/lambdasoup Returns all element ancestors of a node, ordered by proximity (climbing toward the root). Excludes the node itself and the soup node. ```ocaml val ancestors : (_ node) -> element nodes (* src/soup.mli:316 *) ``` -------------------------------- ### Catching Soup.Parse_error Source: https://github.com/aantron/lambdasoup Example of catching Soup.Parse_error when calling select with an invalid selector. The exception is raised at selector parse time, before any traversal, and a missing match is None or Failure, never Parse_error. ```ocaml try soup |> select "[id=unterminated" |> ignore with | Soup.Parse_error message -> Printf.eprintf "bad selector: %s\n" message ``` -------------------------------- ### $$ Source: https://github.com/aantron/lambdasoup Infix (pipeline-friendly) spelling of select. Returns the lazy sequence of all descendants of the given node matching the CSS selector. ```APIDOC ## $$ ### Description Infix (pipeline-friendly) spelling of select. Returns the lazy sequence of all descendants of the given node matching the CSS selector. ### Method Infix Operator ### Signature ```ocaml val ($$) : (_ node) -> string -> element nodes ``` ### Parameters - **node** (`(_ node)`) - Required - Root of the search; any node kind - **selector** (string) - Required - CSS selector; see grammar below ### Returns - `element nodes` (lazy; only as much of the document is walked as needed to satisfy the consumer) ### Throws - `Parse_error of string` for syntactically invalid selectors ### Example ```ocaml open Soup let soup = read_channel stdin |> parse in let links = soup $$ "a[href]" |> to_list in (* all links with href *) ``` ``` -------------------------------- ### Wrap an element and serialize to string Source: https://github.com/aantron/lambdasoup/blob/master/README.md Demonstrates a mutation: parses HTML, wraps the child of the '.Hello' element in a 'strong' element, and serializes the soup back to a string, showing the modified HTML. ```ocaml let soup = parse "

World!

" in wrap (soup $ ".Hello" |> R.child) (create_element "strong"); soup |> to_string;; - : string = "

World!

" ``` -------------------------------- ### trimmed_texts: get trimmed text nodes Source: https://github.com/aantron/lambdasoup Same as texts, but every string is passed through String.trim and empty strings are filtered out. Note that String.trim here is the shadowed, tabs-aware version defined at src/soup.ml:4-29. ```ocaml val trimmed_texts : (_ node) -> string list (* src/soup.mli:275 *) ``` -------------------------------- ### next_siblings and previous_siblings: Get following or preceding siblings Source: https://github.com/aantron/lambdasoup Returns siblings following or preceding a node in the parent's child list. previous_siblings is ordered by proximity to the node, i.e., reverse of document order. ```ocaml val next_siblings : (_ node) -> general nodes (* src/soup.mli:327 *) ``` ```ocaml val previous_siblings : (_ node) -> general nodes (* src/soup.mli:331 *) ``` -------------------------------- ### Combined with open Soup for functional combinators Source: https://github.com/aantron/lambdasoup Demonstrates using Soup.Infix together with open Soup to access functional combinators like parse, R.attribute, and iter. Shows $? returning an option and $$ iterating over all matching elements. Outputs '/2' and then 'one' and 'two' on separate lines. ```ocaml open Soup.Infix open Soup let soup = parse "
" in match soup $? "a[href='/2']" with | Some a -> print_endline (R.attribute "href" a) (* '/2' *) | None -> print_endline "not found"; soup $$ "nav a" |> iter (fun a -> print_endline (R.leaf_text a)) (* one two *) ``` -------------------------------- ### from_signals Source: https://github.com/aantron/lambdasoup Builds a Lambda Soup document from a stream of Markup.ml signals. This underlies `parse`. It is the way to load **XML** into Lambda Soup (Lambda Soup proper only parses HTML), or to feed non-string input. ```APIDOC ## from_signals ### Description Builds a Lambda Soup document from a stream of Markup.ml signals. This underlies `parse`. It is the way to load **XML** into Lambda Soup (Lambda Soup proper only parses HTML), or to feed non-string input. ### Method Function ### Signature ```ocaml val from_signals : (Markup.signal, Markup.sync) Markup.stream -> soup node ``` ### Parameters - **stream** (`(Markup.signal, Markup.sync) Markup.stream`) - Required - Stream of Markup.ml signals ### Returns - **soup node** - Lambda Soup document ### Processing Details - Adjacent text signals are concatenated into single text nodes. - Attribute namespaces other than `""` are preserved by prefixing the name with `ns:`. - Element name namespaces are dropped (the mli notes "Namespaces are ignored at the moment"). - A `Doctype` signal, if present, is stored on the document node and re-emitted by `signals`. ### Example ```ocaml Markup.string s |> Markup.parse_xml |> Markup.signals |> from_signals ``` ``` -------------------------------- ### Canonical scraper pattern using read_channel and write_channel Source: https://github.com/aantron/lambdasoup Reads from stdin, parses, processes, and writes to stdout. Useful for quick scripts that pipe HTML in and out. ```ocaml let () = let soup = read_channel stdin |> parse in let () = (* ...do things to soup... *) in soup |> to_string |> write_channel stdout ``` -------------------------------- ### first Source: https://github.com/aantron/lambdasoup Returns the first member of a node sequence. Equivalent to nth 1 s. ```APIDOC ## first ### Description Returns the first member of a node sequence. Equivalent to nth 1 s. ### Method Function ### Signature ```ocaml val first : 'a nodes -> 'a node option ``` ### Parameters - **s** ('a nodes) - Required - The node sequence to query ### Returns - **'a node option** - The first node if it exists, otherwise None ``` -------------------------------- ### $? Source: https://github.com/aantron/lambdasoup Infix (pipeline-friendly) spelling of select_one. Returns the first element matching the CSS selector, or None if no match exists. ```APIDOC ## $? ### Description Infix (pipeline-friendly) spelling of select_one. Returns the first element matching the CSS selector, or None if no match exists. ### Method Infix Operator ### Signature ```ocaml val ($?) : (_ node) -> string -> element node option ``` ### Parameters - **node** (`(_ node)`) - Required - Root of the search; any node kind - **selector** (string) - Required - CSS selector; see grammar below ### Returns - `element node option` — `Some e` if a match exists, otherwise `None` ### Throws - `Parse_error of string` for syntactically invalid selectors ### Example ```ocaml open Soup let soup = read_channel stdin |> parse in let first_li = soup $? "ul li" in (* option *) ``` ``` -------------------------------- ### Parsing XML with from_signals Source: https://github.com/aantron/lambdasoup Parses XML by converting a string to signals and using from_signals, useful for XML or controlling encoding. Requires Markup.ml. ```ocaml let soup = Markup.string "" |> Markup.parse_xml |> Markup.signals |> Soup.from_signals ``` -------------------------------- ### Modern equivalent using Soup module Source: https://github.com/aantron/lambdasoup Shows the modern equivalent using `open Soup` with identical behavior and no deprecation warning. ```ocaml open Soup let soup = parse "

World!

" in soup $ ".Hello" |> R.leaf_text ``` -------------------------------- ### R.first Source: https://github.com/aantron/lambdasoup Returns the first node in a collection, raising Failure if the collection is empty. ```APIDOC ## [OCaml] R.first ### Description Returns the first node in a collection, raising Failure if the collection is empty. ### Signature ```ocaml val first : 'a nodes -> 'a node ``` ### Parameters - **nodes** ('a nodes) - Required - The collection of nodes ### Returns - **'a node** - The first node ### Throws - **Failure** - with message `Soup.R.first: None` if empty ``` -------------------------------- ### texts: get descendant text nodes Source: https://github.com/aantron/lambdasoup Returns the content of all text nodes that are descendants of the given node, in document order. If the node is itself a text node, returns [content]. Elements contribute nothing themselves; only text descendants are included. ```ocaml val texts : (_ node) -> string list (* src/soup.mli:271 *) ``` -------------------------------- ### R.select_one Source: https://github.com/aantron/lambdasoup Returns the first element matching the CSS selector, raising Failure if none found. ```APIDOC ## [OCaml] R.select_one ### Description Returns the first element matching the CSS selector, raising Failure if none found. ### Signature ```ocaml val select_one : string -> (_ node) -> element node ``` ### Parameters - **selector** (string) - Required - CSS selector string - **node** (_ node) - Required - The node to search within ### Returns - **element node** - The first matching element ### Throws - **Failure** - with message `Soup.R.select_one: None` if no match ### Example ```ocaml let soup = parse "

World!

" in soup |> R.select_one ".Hello" |> R.leaf_text (* - : string = "World!" *) ``` ``` -------------------------------- ### equal function signature Source: https://github.com/aantron/lambdasoup Recursively tests node trees for equality. Tag names must be identical, attributes are compared after sorting by name, children pairwise after normalization, and text after merging adjacent nodes and ignoring empty ones. Class attributes are compared literally. ```ocaml val equal : (_ node) -> (_ node) -> bool (* src/soup.mli:536 *) ``` -------------------------------- ### classes Source: https://github.com/aantron/lambdasoup Returns the element's class list. For example, `
` maps to `["foo"; "bar"]`. Splitting is on the single space character; an element without a `class` attribute yields `[]`. ```APIDOC ## classes ### Description Returns the element's class list. For example, `` maps to `["foo"; "bar"]`. Splitting is on the single space character; an element without a `class` attribute yields `[]`. ### Signature ```ocaml val classes : element node -> string list ``` ### Parameters - **element** (`element node`) - Required - The element ### Returns `string list` ``` -------------------------------- ### signals to emit XML Source: https://github.com/aantron/lambdasoup Converts a node tree into a Markup.ml signal stream, then writes it as XML instead of HTML. Useful when you need XML output from a Lambda Soup document. ```ocaml soup |> signals |> Markup.write_xml |> Markup.to_string ``` -------------------------------- ### One-step traversal shortcuts: parent, child, child_element, next_sibling, previous_sibling, next_element, previous_element Source: https://github.com/aantron/lambdasoup Shortcuts for single-step navigation. parent returns the parent element, or None for root nodes because their parent is the soup node. child and child_element return the first child or first child element. Sibling functions return the next/previous sibling, optionally restricted to elements. ```ocaml val parent : (_ node) -> element node option (* src/soup.mli:424 *) ``` ```ocaml val child : (_ node) -> general node option (* src/soup.mli:442 *) val child_element : (_ node) -> element node option (* src/soup.mli:446 *) ``` ```ocaml val next_sibling : (_ node) -> general node option (* src/soup.mli:450 *) val previous_sibling : (_ node) -> general node option (* src/soup.mli:454 *) val next_element : (_ node) -> element node option (* src/soup.mli:457 *) val previous_element : (_ node) -> element node option (* src/soup.mli:461 *) ``` -------------------------------- ### Basic use of $ operator Source: https://github.com/aantron/lambdasoup Shows basic usage of the $ operator with open Soup.Infix. Parses an HTML string and selects the first element matching the CSS selector '.Hello', then extracts its leaf text. The output is 'World!'. ```ocaml open Soup.Infix let soup = Soup.parse "

World!

" in soup $ ".Hello" |> Soup.R.leaf_text (* - : string = "World!" *) ``` -------------------------------- ### leaf_text: get single text node content Source: https://github.com/aantron/lambdasoup Retrieves the content of one text node inside the node, with specific rules: if the node is a text node, returns Some s; otherwise drops whitespace-only text children and merges adjacent remaining text nodes. Returns Some "" for 0 children, leaf_text of the child for 1 child (recursion unwraps nested elements), and None for 2+ children. ```ocaml val leaf_text : (_ node) -> string option (* src/soup.mli:279 *) ``` -------------------------------- ### select_one Source: https://github.com/aantron/lambdasoup Returns the first element matching the CSS selector, or None if no match exists. Limited to at most one element. ```APIDOC ## select_one ### Description Returns the first element matching the CSS selector, or None if no match exists. Limited to at most one element. ### Method Function ### Signature ```ocaml val select_one : string -> (_ node) -> element node option ``` ### Parameters - **selector** (string) - Required - CSS selector; see grammar below - **node** (`(_ node)`) - Required - Root of the search; any node kind ### Returns - `element node option` — `Some e` if a match exists, otherwise `None` ### Throws - `Parse_error of string` for syntactically invalid selectors ### Example ```ocaml open Soup let soup = read_channel stdin |> parse in let first_li = soup $? "ul li" in (* option *) ``` ``` -------------------------------- ### val name : element node -> string Source: https://github.com/aantron/lambdasoup Returns the element's tag name, lowercased. Input tag names are converted by Markup.ml and `name` applies `String.lowercase_ascii`. ```ocaml val name : element node -> string (* src/soup.mli:233 *) ``` -------------------------------- ### to_string Source: https://github.com/aantron/lambdasoup Converts the node tree rooted at the given node to an HTML5 string, preserving whitespace nodes. Implemented as `signals root |> Markup.write_html |> Markup.to_string`. ```APIDOC ## to_string ### Description Converts the node tree rooted at the given node to an **HTML5** string, preserving whitespace nodes. Implemented as `signals root |> Markup.write_html |> Markup.to_string`. ### Method Function ### Signature ```ocaml val to_string : (_ node) -> string ``` ### Parameters - **node** (`_ node`) - Required - Root node to serialize ### Returns - **string** - HTML5 string representation of the node tree ### Example ```ocaml open Soup let soup = parse "

Hello

" in to_string soup (* - : string = "

Hello

" *) ``` ``` -------------------------------- ### write_channel Source: https://github.com/aantron/lambdasoup Writes the given data to the output channel. Flush with flush if needed. ```APIDOC ## write_channel ### Description Writes the given data to the output channel. Flush with `flush` if needed. ### Signature ```ocaml val write_channel : out_channel -> string -> unit ``` ### Parameters - **channel** (out_channel) - Required - The output channel to write to. - **data** (string) - Required - The data to write to the channel. ### Example ```ocaml let soup = read_channel stdin |> parse in let () = (* ...do things to soup... *) in soup |> to_string |> write_channel stdout ``` ``` -------------------------------- ### CSS selection functions: select, select_one, $$, $?, $ Source: https://github.com/aantron/lambdasoup select returns a lazy sequence of matching element nodes; select_one limits to at most one. $$, $?, and $ are infix spellings. Only element nodes are produced; a soup/text root never matches. $ raises Failure if no match is found. ```ocaml val select : string -> (_ node) -> element nodes (* src/soup.mli:114 *) val select_one : string -> (_ node) -> element node option (* src/soup.mli:143 *) val ($$) : (_ node) -> string -> element nodes (* src/soup.mli:148 *) val ($?) : (_ node) -> string -> element node option (* src/soup.mli:151 *) val ($) : (_ node) -> string -> element node (* src/soup.mli:154 *) ``` -------------------------------- ### Tag convenience function signatures (tags and tag) Source: https://github.com/aantron/lambdasoup Declares the `tags` and `tag` functions for finding descendant elements by tag name. `tags` returns all matching elements, `tag` returns the first one. Tag matching is case-insensitive. ```ocaml val tags : string -> (_ node) -> element nodes (* src/soup.mli:403 *) val tag : string -> (_ node) -> element node option (* src/soup.mli:421 *) ``` -------------------------------- ### R.tag Source: https://github.com/aantron/lambdasoup Returns the first element with the given tag name, raising Failure if none found. ```APIDOC ## [OCaml] R.tag ### Description Returns the first element with the given tag name, raising Failure if none found. ### Signature ```ocaml val tag : string -> (_ node) -> element node ``` ### Parameters - **tag** (string) - Required - Tag name to search for - **node** (_ node) - Required - The node to search within ### Returns - **element node** - The first matching element ### Throws - **Failure** - with message `Soup.R.tag: None` if no match ``` -------------------------------- ### read_file Source: https://github.com/aantron/lambdasoup Reads the entire contents of a file at the given path. Raises Sys_error on failure. ```APIDOC ## read_file ### Description Reads the entire file at the given path. Raises `Sys_error` on failure. ### Signature ```ocaml val read_file : string -> string ``` ### Parameters - **path** (string) - Required - The path to the file to read. ### Return Value Returns the contents of the file as a string. ### Exceptions - **Sys_error** - Raised if the file cannot be read. ### Example ```ocaml try read_file "/nonexistent" |> ignore with | Sys_error message -> Printf.eprintf "could not read file: %s\n" message ``` ``` -------------------------------- ### write_file Source: https://github.com/aantron/lambdasoup Writes data to a file at the given path, truncating the file if it exists. Raises Sys_error on failure. ```APIDOC ## write_file ### Description Writes the given data to the file at the specified path, truncating the file if it already exists. Raises `Sys_error` on failure. To append, open a channel with `open_out_gen` and pass it to `write_channel`. ### Signature ```ocaml val write_file : string -> string -> unit ``` ### Parameters - **path** (string) - Required - The path to the file to write to. - **data** (string) - Required - The data to write to the file. ### Exceptions - **Sys_error** - Raised if the file cannot be written. ``` -------------------------------- ### $ Source: https://github.com/aantron/lambdasoup Infix operator that selects the first element matching a CSS selector and returns it, raising Failure if no match is found. Equivalent to `select_one selector node |> require`. ```APIDOC ## $ operator ### Description Infix operator that selects the first element matching a CSS selector and returns it, raising Failure if no match is found. Equivalent to `select_one selector node |> require`. ### Signature `val ($) : (_ node) -> string -> element node` ### Parameters - **node** (`(_ node)`) - Required - Root of the selection; any node kind - **selector** (string) - Required - CSS selector ### Returns - `element node` - First matching element ### Raises - `Failure` - When no match is found. Message: `Soup.($): '' not found.` + hint. ### Example ```ocaml open Soup.Infix let soup = Soup.parse "

World!

" in soup $ ".Hello" |> Soup.R.leaf_text (* - : string = "World!" *) ``` ``` -------------------------------- ### read_channel Source: https://github.com/aantron/lambdasoup Reads all bytes from the given input channel. Useful for reading from stdin or other channels. ```APIDOC ## read_channel ### Description Reads all bytes from the given input channel. ### Signature ```ocaml val read_channel : in_channel -> string ``` ### Parameters - **channel** (in_channel) - Required - The input channel to read from. ### Return Value Returns the contents of the channel as a string. ### Example ```ocaml let soup = read_channel stdin |> parse in let () = (* ...do things to soup... *) in soup |> to_string |> write_channel stdout ``` ``` -------------------------------- ### create_soup Source: https://github.com/aantron/lambdasoup Creates a new empty document node (no roots, no doctype). ```APIDOC ## create_soup ### Description Creates a new empty document node (no roots, no doctype). ### Signature ```ocaml val create_soup : unit -> soup node ``` ### Parameters None. ### Returns `soup node`. ``` -------------------------------- ### append_root and prepend_root signatures Source: https://github.com/aantron/lambdasoup OCaml signatures for adding a node as the last or first root of a document. The node is deleted from its previous location first and its parent is set to the document. ```ocaml val append_root : soup node -> (_ node) -> unit (* src/soup.mli:642 *) val prepend_root : soup node -> (_ node) -> unit (* src/soup.mli:645 *) ```