[Golang] HTML Table to reStructuredText list-table via goquery


Introduction

Convert HTML table to reStructuredText list-table via goquery in Golang (Go programming language). For unrobust implementation via Go net/html package, see [5]. For Python Beautiful Soup 4 (bs4) implementation, see [4].

Install goquery

$ go get -u github.com/PuerkitoBio/goquery

HTML table to reStructuredText list-table

goquery.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package table2rst

import (
	"bufio"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"os"
	"strings"
)

func StringToLines(s string) []string {
	var lines []string

	scanner := bufio.NewScanner(strings.NewReader(s))
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}

	return lines
}

func rstListTablePrefixOfEachLine(indexOfTd, indexOfLine int) string {
	if indexOfTd == 0 {
		if indexOfLine == 0 {
			return "   * - "
		} else {
			return "       "
		}
	} else {
		if indexOfLine == 0 {
			return "     - "
		} else {
			return "       "
		}
	}
}

func processTr(tr *goquery.Selection, fRstOutput *os.File) {
	tr.Find("td").Each(func(indexOfTd int, td *goquery.Selection) {
		lines := StringToLines(td.Text())
		for indexOfLine, line := range lines {
			line = strings.TrimSpace(line)
			fmt.Fprintf(fRstOutput, rstListTablePrefixOfEachLine(indexOfTd, indexOfLine))
			fmt.Fprintf(fRstOutput, line)
			fmt.Fprintf(fRstOutput, "\n")
		}
	})
}

func htmlTableToRst(url, outputFilePath string) {
	doc, err := goquery.NewDocument(url)
	if err != nil {
		panic(err)
	}

	fRstOutput, err := os.Create(outputFilePath)
	if err != nil {
		panic(err)
	}

	doc.Find("table").Each(func(_ int, table *goquery.Selection) {
		fmt.Fprintf(fRstOutput, ".. list-table:: \n\n")
		table.Find("tr").Each(func(_ int, tr *goquery.Selection) {
			processTr(tr, fRstOutput)
		})
		fmt.Fprintf(fRstOutput, "\n\n")
		fmt.Fprintf(fRstOutput, "|\n|\n\n")
	})
}

Usage:

goquery_test.go | repository | view raw
1
2
3
4
5
6
7
8
9
package table2rst

import (
	"testing"
)

func TestTable2Rst(t *testing.T) {
	htmlTableToRst("http://nanda.online-dhamma.net/Tipitaka/Sutta/Majjhima/mn.047.contrast-reading.html", "output.rst")
}

Tested on: Ubuntu Linux 15.10, Go 1.6.


References:

[1]jquery iterate over elements - Google search
[2]
[3]github.com/PuerkitoBio/goquery - GoDoc
[4][Python] Convert HTML Table to reStructuredText list-table
[5][Golang] Unrobust HTML Table to reStructuredText list-table
[6]html table to rst list-table · twnanda/twnanda@e022835 · GitHub
[7]go - How to convert HTML table to array with golang - Stack Overflow