HTML documents
The html type holds an HTML document, parsed the way web browsers parse it. html.parse(text) reads one from text, html.load(f) from a file. Printing it, or putting it in ${...}, writes it back as HTML:
page: html = html.parse("<title>Shop</title><p class=lead>Fresh <b>bread")
print(page)Output:
<html><head><title>Shop</title></head><body><p class="lead">Fresh <b>bread</b></p></body></html>| Function or method | What it gives |
|---|---|
html.parse(text) | the document in a str |
html.load(f) | the document in a file |
h.find(selector) | the elements under h that match a CSS selector, in the page’s order: an [html] |
h.first(selector) | the first of them, or nil: an ?html |
h.tag() | an element’s name, lower case: "a", "li" ("" for a document) |
h.text() | the text a browser shows, with line breaks between blocks |
h.attr(name) | an attribute’s value, "" if it hasn’t it |
h.has(name) | whether it has the attribute |
h.attrs() | all of them, a {str: str} in their order |
h.children() | the elements right inside it, an [html] |
h.parent() | what it is in (nil for a document), an ?html |
h.html() | the element with its tags, or the whole document, as HTML text; print(h) writes the same |
h.markdown() | the element or document as Markdown |
And to change a page (see Changing a page):
| Function or method | What it does |
|---|---|
h.text(s) | the element holds only the text s |
h.html(s) | the element holds the HTML s, parsed in it as browsers parse innerHTML (a whole document’s: a new page) |
h.set(name, value), h.drop(name) | gives an attribute a value; removes one |
h.add(e), h.add(s) | puts an element, or text, at the end of this one |
h.remove() | takes the element out of its page |
h.copy() | a copy of the element and all in it, in no page yet |
h.clear() | empties the element |
html.make(name) | a new element, html.make("li") |
Searching: CSS selectors
find and first take the selectors of CSS and of document.querySelectorAll in browsers. Each value found is an element, which can be searched again:
page: html = html.parse("<h1>Books</h1><ul id=list><li class=book><a href='/dune'>Dune</a> <span class=price>9.50</span><li class='book sale'><a href='/emma'>Emma</a> <span class=price>4.00</span></ul>")
page.find("li.book").walk(b) {
link: ?html = b.first("a")
price: ?html = b.first(".price")
if link != nil && price != nil {
print("${link.text()}: ${price.text()} (${link.attr("href")})")
}
}
print(page.find(".sale a"))Output:
Dune: 9.50 (/dune)
Emma: 4.00 (/emma)
[<a href="/emma">Emma</a>]| Selector | Matches |
|---|---|
li, * | elements of that name (the case doesn’t matter), any element |
#list, .book | the element whose id is list; those with the class book among their classes |
[href] | those with the attribute |
[lang=en], [class~=sale], [lang|=en] | the value is en; one of its words is sale; it is en or starts with en- |
[href^=https], [href$=".pdf"], [title*=news] | the value starts with, ends with, or has in it (in quotes if it has spaces or dots) |
[type=TEXT i] | the same, whatever the case of the letters |
ul li, ul > li | an li somewhere inside a ul; right inside it |
h1 + p, h1 ~ p | the p right after an h1; any p after one, beside it |
:first-child, :last-child, :only-child | the first, last or only element in what it is in |
:nth-child(2), :nth-child(odd), :nth-child(3n+1), :nth-last-child(-n+2) | by its place, counted from 1 (from the end for nth-last-child) |
:empty | no elements or text inside |
:not(.sale, #top) | none of these |
h1, h2 | either |
A selector that isn’t right, like li:hover or p,, stops the program with error 11, which says what is wrong. find searches what is inside h, but the selector is matched against the whole page: b.find("ul li") finds the lis inside b that are inside a ul, even one around b.
Selectors were checked against soupsieve, BeautifulSoup’s CSS engine, on random pages and selectors. They differ in one place, where Luma follows browsers: an element holding only white space isn’t :empty.
Text and Markdown
text() gives the text as a browser shows it (the way innerText does): white space runs become one space, each block (a paragraph, heading, list item, table row…) is on lines of its own, with a blank line around paragraphs and headings, table cells are apart by tabs, <br> is a line break, and <pre> keeps its text as it is. What a browser doesn’t show is left out: <head>, scripts, styles, templates.
markdown() writes the same as Markdown (CommonMark, with GitHub’s tables and ~~), ready for a language model or a README: headings, bold and italics, code, links and images, lists (nested, with their numbers), quotes >, code blocks with their language (from class="language-go"), tables with their first row as the header, and ---. Characters Markdown would read as its own are escaped, so the text stays text. Forms, scripts and other things without a Markdown form are left out.
page: html = html.parse("<h1>Report</h1><p>Sales grew\n by <b>12%</b>.<br>See below.</p><table><tr><th>Region<th>Sales<tr><td>North<td>120</table>")
print(page.text())
print("--")
print(page.markdown())Output:
Report
Sales grew by 12%.
See below.
Region Sales
North 120
--
# Report
Sales grew by **12%**.\
See below.
| Region | Sales |
| --- | --- |
| North | 120 |The Markdown was checked by rendering it back to HTML with markdown-it (on random pages): it gives the same elements and text.
Parsed as browsers parse it
Real pages are rarely tidy: tags are left open, closed in the wrong order, put where they don’t belong. The HTML standard (WHATWG’s HTML Living Standard) says exactly what a browser makes of every such page, and Luma follows it step by step, so a page gives the same tree in Luma as in Chrome or Firefox:
- Missing
<html>,<head>and<body>are added, and elements that end by themselves (<p>,<li>,<td>, …) are closed where the next one starts. - Tags closed in the wrong order are mended as browsers mend them:
<b>1<p>2</b>3</p>gives<b>1</b><p><b>2</b>3</p>. - Text and tags that don’t belong inside a
<table>are moved before it. - Character references are read, with or without
;:©,©,©and©all give ©. - SVG and MathML keep the case of their names (
viewBox,foreignObject). <script>,<style>and<textarea>keep their text as it is; a<template>keeps its content apart.
print(html.parse("<b>1<p>2</b>3</p>"))
print(html.parse("<table>x<tr><td>1<td>2</table>"))
print(html.parse("<p>© © © A < B"))Output:
<html><head></head><body><b>1</b><p><b>2</b>3</p></body></html>
<html><head></head><body>x<table><tbody><tr><td>1</td><td>2</td></tr></tbody></table></body></html>
<html><head></head><body><p>© © © A < B</p></body></html>The parser passes the tree-construction and tokenizer tests of html5lib-tests, which browsers use too: 1,784 documents and 7,032 tokenizer cases.
Changing a page
An html value is a place in its page, not a copy of it: changing what page.first("h1") gives changes page, as in a browser. find gives the elements as they are when it is called, so a walk over them can change or remove them.
text(s)andset(name, value)put text in as text:<,&and"in it are escaped when the page is written. A visitor’s name can’t become HTML. Onlyhtml(s)reads HTML, and it says so.addmoves an element that is already in the same page, as browsers do, and puts in a copy of one from another page or fromhtml.make, so two pages never share an element.- An element can’t be added inside itself, and a whole document can’t be added to an element (
html(s)takes a page’s HTML). These, a namesetcan’t have ("a b") and a namehtml.makecan’t have, stop the program with error 11. remove()takes an element out, with all in it; the value stays usable, andaddcan put it back or elsewhere.
The changes were checked against html5lib’s DOM: random changes to random pages give the same trees.
Pages from templates
A page’s HTML is its own template: there is no {{ }} language to learn. Write a sample of the page, with a sample row, and fill it with selectors. Here find(...).walk fills every match, and none if there is none:
page: html = html.parse("<h1>Books</h1><ul id=books><li class=book><span class=title>Sample</span> <a href=#>more</a></ul>")
books: [str] = ["Dune", "Fish & <Chips>"]
list: ?html = page.first("#books")
sample: ?html = page.first("li.book")
if list != nil && sample != nil {
sample.remove()
n: int = 1
books.walk(name) {
row: html = sample.copy()
row.find(".title").walk(x) {
x.text(name)
}
row.find("a").walk(x) {
x.set("href", "/book?id=${n}")
}
list.add(row)
n = n + 1
}
}
print(page)Output:
<html><head></head><body><h1>Books</h1><ul id="books"><li class="book"><span class="title">Dune</span> <a href="/book?id=1">more</a></li><li class="book"><span class="title">Fish & <Chips></span> <a href="/book?id=2">more</a></li></ul></body></html>In a web server the template comes from a file, and http.html(page) answers with it:
fn books(req: http.request): http.response {
page: html = html.load(file("templates/books.html"))
...
return http.html(page)
}Load the template for each answer (or copy() one loaded at the start): filling it changes it.
Escaping makes text safe in an element and in an attribute’s value, but not every value is safe: a link a visitor gives can be javascript:.... Check the URLs you take from outside before you set them as an href.
Writing HTML back
h.html() writes the document as the standard’s serializer does: attributes in "...", &, <, > and the no-break space escaped as &, <, > and (in attribute values " as " too), no end tags for void elements (<br>, <img>, <input>, …), and the text of <script> and <style> as it is. Comments and the doctype stay where they were.
Good to know
- The text is read as UTF-8. Bytes that aren’t UTF-8 become U+FFFD (�); a page in another encoding is converted before it is parsed. Line breaks
\r\nand\rbecome\n, as in browsers. - Pages are parsed as browsers parse them with scripting off: what is in
<noscript>is part of the page. Scripts don’t run. - Parsing is quick in built programs: a 1 MB page takes about 0.3 seconds.
luma runtakes about 3 seconds for it.