Skip to content
mhpentaPublic

About

Extract plaintext, cleaned tables, repeated records, and source maps from HTML in Go.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

htmldoc

Extract plaintext, tables, repeated records, and source maps from static UTF-8 HTML. Requires Go 1.26+.

import "github.com/mhpenta/htmldoc"

Quick start

All entry points accept optional htmldoc.Option functions (WithMainContent, WithSelector, WithDivGrids, etc.).

Plaintext

text, err := htmldoc.PlainText(ctx, htmlBytes)

// Scope to main content and render images as Markdown:
text, err = htmldoc.PlainText(ctx, htmlBytes,
	htmldoc.WithMainContent(),
	htmldoc.WithImagesAsMarkdown(true),
)

// Render table cells as prose instead of inline CSV:
text, err = htmldoc.PlainText(ctx, htmlBytes, htmldoc.WithoutCSVTables())

Tables

tables, err := htmldoc.Tables(ctx, htmlBytes)

// Discover div grids with labels and three-row CSV previews:
tables, err = htmldoc.Tables(ctx, htmlBytes,
	htmldoc.WithMainContent(),
	htmldoc.WithDivGrids(true),
	htmldoc.WithTableLabels(true),
	htmldoc.WithPreviewOnly(true),
)

Table.SourceNumber is 1-based across all HTML tables in document order (0 for inferred div grids); Table.PublishedNumber is 1-based across returned tables.

Repeated records

groups, err := htmldoc.Records(ctx, htmlBytes,
	htmldoc.WithMainContent(),
	htmldoc.WithMaxRecordGroups(5),
)

Source maps

ParseSourceMap returns unnormalized visible text with block byte ranges and text-node spans for mapping citations or highlights back to exact HTML text nodes without retaining DOM pointers:

sm, err := htmldoc.ParseSourceMap(ctx, htmlBytes, htmldoc.WithMainContent())
if err != nil {
	return err
}

ranges, err := sm.NodeRanges(start, end)
for _, r := range ranges {
	nodeText, _ := sm.NodeText(r.NodeID)
	_ = nodeText[r.Start:r.End]
}

Parse once, extract many times

Use Parse to run multiple queries against one document, or page.Extract to request several outputs in a single pass while sharing table expansion work:

page, err := htmldoc.Parse(ctx, htmlBytes, &htmldoc.ParseOptions{
	Name: "filing.htm",
}) // pass nil for defaults
if err != nil {
	return err
}

res, err := page.Extract(ctx, htmldoc.Request{
	Scope:      htmldoc.ScopeMain(),
	TableRules: htmldoc.TableRules{DivGrids: true},
	Text:       &htmldoc.TextOptions{},
	Tables:     &htmldoc.TableOptions{IncludeLabel: true},
	SourceMap:  true,
})
if err != nil {
	return err
}

fmt.Println(res.Text)
fmt.Println(res.Tables[0].CSV)
fmt.Println(res.SourceMap.Text)

*Page is safe for concurrent use and also provides PlainText, Tables, Records, and SourceMap. Set custom exclusions in ParseOptions.Visibility and byte caps in ParseOptions.Limits.

Concurrency, timeouts, and limits

Package-level helpers (PlainText, Tables, Records, ParseSourceMap) share a default Extractor (4 concurrent calls, 60s post-admission timeout, and 10 MiB input / 64 MiB expanded / 64 MiB output limits). Create an Extractor to customize these bounds:

ext := htmldoc.New(&htmldoc.ExtractorOptions{
	MaxConcurrency: 4,
	Timeout:        30 * time.Second,
	Limits:         htmldoc.Limits{MaxInputBytes: 32 << 20},
})

tables, err := ext.Tables(ctx, htmlBytes, htmldoc.WithTableLabels(true))

Any error discards the entire result. Use errors.Is for sentinel errors and errors.As with *TableLimitError or *OutputLimitError for details.

Extracting tables from an SEC filing

CleanFinancial is enabled by default, so inline XBRL headers are omitted and split currency, sign, and percent columns are merged automatically. For large 10-K filings (> 10 MiB), use a custom Extractor with a higher MaxInputBytes.

filingHTML, err := os.ReadFile("10-k.htm")
if err != nil {
	return err
}

tables, err := htmldoc.Tables(ctx, filingHTML, htmldoc.WithTableLabels(true))
if err != nil {
	return err
}

for _, t := range tables {
	fmt.Printf("Table %d (HTML #%d): %s (%dx%d)\n%s\n",
		t.PublishedNumber, t.SourceNumber, t.Label, t.RowCount, t.ColCount, t.CSV)
}

Sample CSV output (from the NVIDIA Q2 FY2025 income statement fixture):

,Three Months Ended,Three Months Ended,Six Months Ended,Six Months Ended
,"July 28,","July 30,","July 28,","July 30,"
,2024,2023,2024,2023
Revenue,"$30,040","$13,507","$56,084","$20,699"
Cost of revenue,"7,466","4,045","13,105","6,589"
Gross profit,"22,574","9,462","42,979","14,110"

Financial table tests

Run go test ./... from the module root to verify rows, column counts, table order, and exact CSV across 79 tables in 14 HTML inputs, plus regressions for NVIDIA’s income statement indentation and JPMorgan’s reported/managed 10-K measures (financial fixtures).

Options

Functional Option helpers are defined in options.go; struct options (ParseOptions, ExtractorOptions, Request, TableRules, TextOptions, TableOptions, RecordOptions) are defined in api.go.

  • Scope: WithScope, WithMainContent, WithSelector
  • Plaintext: WithImagesAsMarkdown, WithCSVTables, WithoutCSVTables
  • Table rules: WithCSVDelimiter, WithDivGrids, WithCleanMode (CleanFinancial / CleanMinimal), WithMaxLinks
  • Tables: WithTableLabels, WithLabelFunc, WithPreviewOnly, WithPreviewRows, WithKeepSingleRow, WithIncludeHTML
  • Records: WithMaxRecordGroups, WithPreviewRecords, WithIncludeHTML

About

Extract plaintext, cleaned tables, repeated records, and source maps from HTML in Go.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages