Web ページの表をスプレッドシートに移すとき、<tr> ごとに <td> の文字を並べて CSV にする処理はよく書かれる。単純な表ならこれで足りるが、縦に結合したセル(rowspan)があると、結合された下の行ではセルが1つ少なくなり、残りの値が1列ずつ左へずれる。
この記事では、ハシトシステムの HTMLの表をCSVに変換 が表をどう読んでいるかを確かめ、HTML Living Standard の表の決まり、pandas の read_html と比べる。最後に、rowspan を展開して列をそろえる関数を書く。
検証環境は Windows 11、Node.js v24.11.1、jsdom 29.1.1、Python 3.11.9、pandas 3.1.1、lxml 6.2.0 である。
ツールの読み方
公開中のページのスクリプト(2026-11-29 確認)は次のように動く。
- 貼り付けた HTML を
DOMParser で読み、table 要素をすべて探す。入れ子の表も1つの表として数える。
- 表ごとに
table.querySelectorAll('tr') で行を集め、行ごとに querySelectorAll('th,td') でセルを集める。
colspan は指定された数だけ空のセルを後ろに足す。rowspan は展開しない(ページの FAQ にもそう書かれている)。
- セルの値は
textContent。「余分な空白・改行をまとめる」がオンなら連続する空白を1つにする。
querySelectorAll は子孫をすべて拾うので、入れ子の表の行やセルも外側の表の行・セルとして数えられる。ここから以下の現象が出てくる。
HTML の表の決まり
HTML Living Standard の表の節には、次のことが書かれている。
colspan は 1 以上 1000 以下、rowspan は 0 以上 65534 以下。
rowspan="0" は「その行グループ(thead / tbody / tfoot)の残りの行すべてにまたがる」という意味になる。
table.rows は thead の行、table 直下と tbody の行、tfoot の行の順に並ぶ。ソースの順ではない。
- 現在の仕様では
tfoot は tbody の後ろに置く。一方、HTML 4.01(11.2.3)では tfoot を tbody より前に書く決まりだったので、古いページには tbody より前に tfoot があるものが残っている。
ブラウザはこの決まりに沿って、セルを行と列の格子に置いていく。上の行の rowspan がすでに埋めている位置は飛ばして、次の空いている列にセルを置く。行ごとにセルを並べるだけの処理は、この「飛ばす」をしていないので列がずれる。
実際に試す
準備
1 2 3 4 5 6
| mkdir htmltable && cd htmltable npm init -y npm install jsdom curl -s -o live.html https://hashitosystem.com/tools/htmltablecsv/ python -m venv venv venv\Scripts\python -m pip install pandas lxml
|
macOS / Linux では最後の行を venv/bin/python -m pip install pandas lxml にする。
ページのスクリプトから、画面に依存しない関数だけを取り出して Node.js で動かす。$ は「余分な空白・改行をまとめる」のチェック欄を返す関数なので、常にオンとして差し替える。
1 2 3 4 5 6 7 8 9 10 11 12
| import { readFileSync } from 'node:fs'; import vm from 'node:vm';
const html = readFileSync('live.html', 'utf8'); const start = html.indexOf('function cellText'); const end = html.indexOf('function render()'); const ctx = { $: () => ({ checked: true }) }; vm.createContext(ctx); vm.runInContext(html.slice(start, end), ctx);
export const { tableToRows, quote } = ctx;
|
試す表を6つ用意する。
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
| export const samples = { rowspan: `<table> <tr><th>地域</th><th>店舗</th><th>売上</th></tr> <tr><td rowspan="2">東京</td><td>渋谷</td><td>120</td></tr> <tr><td>新宿</td><td>95</td></tr> <tr><td>大阪</td><td>梅田</td><td>80</td></tr> </table>`, both: `<table> <tr><th rowspan="2">店舗</th><th colspan="2">売上</th></tr> <tr><th>上期</th><th>下期</th></tr> <tr><td>渋谷</td><td>60</td><td>60</td></tr> </table>`, nested: `<table> <tr><th>商品</th><th>内訳</th></tr> <tr><td>セットA</td><td><table><tr><td>ペン</td><td>2</td></tr></table></td></tr> </table>`, br: `<table> <tr><th>名前</th><th>住所</th></tr> <tr><td>山田<span style="display:none">(旧姓 佐藤)</span></td><td>東京都<br>渋谷区</td></tr> </table>`, tfoot: `<table> <thead><tr><th>月</th><th>件数</th></tr></thead> <tfoot><tr><td>合計</td><td>30</td></tr></tfoot> <tbody><tr><td>1月</td><td>10</td></tr><tr><td>2月</td><td>20</td></tr></tbody> </table>`, zero: `<table> <tr><th>区分</th><th>項目</th></tr> <tr><td rowspan="0">共通</td><td>A</td></tr> <tr><td>B</td></tr> <tr><td>C</td></tr> </table>`, };
|
ツールの関数に通す
1 2 3 4 5 6 7 8 9 10 11
| import { JSDOM } from 'jsdom'; import { tableToRows, quote } from './tool.mjs'; import { samples } from './samples.mjs';
const name = process.argv[2]; const { document } = new JSDOM(samples[name]).window; const tables = document.querySelectorAll('table'); console.log(`tables=${tables.length}`); const rows = tableToRows(tables[0]); for (const r of rows) console.log(r.map(c => quote(c, ',')).join(','));
|
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
| $ node run-tool.mjs rowspan tables=1 地域,店舗,売上 東京,渋谷,120 新宿,95 大阪,梅田,80
$ node run-tool.mjs both tables=1 店舗,売上, 上期,下期 渋谷,60,60
$ node run-tool.mjs nested tables=2 商品,内訳 セットA,ペン2,ペン,2 ペン,2
$ node run-tool.mjs br tables=1 名前,住所 山田(旧姓 佐藤),東京都渋谷区
$ node run-tool.mjs tfoot tables=1 月,件数 合計,30 1月,10 2月,20
$ node run-tool.mjs zero tables=1 区分,項目 共通,A B C
|
読み取れることを挙げる。
- rowspan: 3行目の
新宿,95 は2列しかなく、新宿 が「地域」の列に、95 が「店舗」の列に入った。表計算ソフトに貼ると、この行だけ1列左にずれる。
- both: 見出しが2段の表では、2段目の
上期,下期 が1列目から始まり、「店舗」の下に「上期」が来た。colspan の空セルは正しく足されている。
- nested: 入れ子の表の行が外側の表の行として1行増え、外側のセルの値は内側のセルの文字をつないだ
ペン2 になった。そのうえ内側の ペン と 2 が外側の行にも並んだ。表の数も2と数えられる。
- br:
<br> は textContent に何も残さないので、東京都渋谷区 とつながった。display:none の (旧姓 佐藤) も値に入った。画面では見えない文字である。
- tfoot: ソースの順に読むので、
tbody の前に書かれた合計行が見出しのすぐ下に来た。ブラウザの表示では合計行は一番下にある。
- zero:
rowspan="0" も展開されないので、B と C が「区分」の列に入った。
pandas.read_html と比べる
1 2 3 4 5 6 7 8 9 10 11 12 13
| import io, json, subprocess, sys import pandas as pd
sys.stdout.reconfigure(encoding="utf-8") samples = json.loads(subprocess.run( ["node", "-e", "import('./samples.mjs').then(m => process.stdout.write(JSON.stringify(m.samples)))"], capture_output=True, text=True, encoding="utf-8", check=True).stdout)
for name in ["rowspan", "both", "nested", "br", "tfoot", "zero"]: dfs = pd.read_html(io.StringIO(samples[name])) print(f"== {name} tables={len(dfs)}") print(dfs[0].to_csv(index=False, lineterminator="\n").strip())
|
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
| $ venv\Scripts\python pd.py == rowspan tables=1 地域,店舗,売上 東京,渋谷,120 東京,新宿,95 大阪,梅田,80 == both tables=1 店舗,売上,売上 店舗,上期,下期 渋谷,60,60 == nested tables=2 商品,内訳 セットA,ペン2 == br tables=1 名前,住所 山田,東京都 渋谷区 == tfoot tables=1 月,件数 1月,10 2月,20 合計,30 == zero tables=1 区分,項目 共通,A B, C,
|
rowspan と colspan は、結合されたすべての位置に同じ値をコピーして展開した。2段見出しは列ごとに 店舗,店舗 売上,上期 売上,下期 の組になる。
- 入れ子の表は外側の行を増やさず、別の表として
dfs[1] に入った。外側のセルの値は ペン2 で、ツールと同じくつながっている。
display:none の要素は既定(displayed_only=True)で読まれず、<br> は空白になった。
tfoot の行は最後に来た。
rowspan="0" は展開されず、B と C が1列目に入った。pandas でもここは仕様どおりにならない。
格子に置いて列をそろえる
table.rows と row.cells を使うと、入れ子の表の行は入らず、tfoot も最後になる。あとは上の行の rowspan が埋めた位置を飛ばしながらセルを置けばよい。
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
| import { JSDOM } from 'jsdom'; import { samples } from './samples.mjs';
function cellText(cell) { const c = cell.cloneNode(true); c.querySelectorAll('table').forEach(t => t.replaceWith(Array.from(t.querySelectorAll('th,td'), x => x.textContent.trim()).join(' '))); c.querySelectorAll('script,style,[hidden],[style*="display:none"]').forEach(e => e.remove()); c.querySelectorAll('br').forEach(b => b.replaceWith('\n')); return c.textContent.replace(/ /g, ' ').replace(/[ \t\r\f]+/g, ' ') .split('\n').map(s => s.trim()).join('\n').trim(); }
function toGrid(table, { fill = 'copy' } = {}) { const rows = Array.from(table.rows); const grid = []; rows.forEach((tr, y) => { grid[y] ??= []; let x = 0; for (const cell of tr.cells) { while (grid[y][x] !== undefined) x++; const cs = Math.min(Math.max(cell.colSpan, 1), 1000); let rs = cell.rowSpan; if (rs === 0) { const group = tr.parentElement; rs = rows.slice(y).filter(r => r.parentElement === group).length; } const text = cellText(cell); for (let dy = 0; dy < rs; dy++) { grid[y + dy] ??= []; for (let dx = 0; dx < cs; dx++) { const first = dy === 0 && dx === 0; grid[y + dy][x + dx] = first || fill === 'copy' ? text : ''; } } x += cs; } }); const width = Math.max(...grid.map(r => r.length)); return grid.slice(0, rows.length).map(r => Array.from({ length: width }, (_, i) => r[i] ?? '')); }
const q = v => (/[",\r\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v); const [name, fill = 'copy'] = process.argv.slice(2); const { document } = new JSDOM(samples[name]).window; const table = document.querySelector('table'); for (const r of toGrid(table, { fill })) console.log(r.map(q).join(','));
|
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
| $ node grid.mjs rowspan 地域,店舗,売上 東京,渋谷,120 東京,新宿,95 大阪,梅田,80
$ node grid.mjs rowspan blank 地域,店舗,売上 東京,渋谷,120 ,新宿,95 大阪,梅田,80
$ node grid.mjs both blank 店舗,売上, ,上期,下期 渋谷,60,60
$ node grid.mjs nested 商品,内訳 セットA,ペン 2
$ node grid.mjs br 名前,住所 山田,"東京都 渋谷区"
$ node grid.mjs tfoot 月,件数 1月,10 2月,20 合計,30
$ node grid.mjs zero 区分,項目 共通,A 共通,B 共通,C
|
6つの表すべてで列がそろった。fill を blank にすると、結合された位置の2つ目以降を空にする。並べ替えや集計に使うなら値をコピーする copy、見た目どおりに貼りたいなら blank が向く。<br> を改行として残したセルは二重引用符で囲まれるので、改行を含む値を読める CSV のパーサーで読む。
jsdom の rowSpan は rowspan="0" に対して 0 を返した。仕様の IDL でも rowSpan の範囲は 0〜65534、colSpan は 1〜1000 と決められている。
どう使うか
- 結合の無い表なら、HTMLの表をCSVに変換 にページのソースを貼るだけで CSV になる。表が複数あれば一覧から選べる。
- 変換結果の「最大列数」と、行ごとの値の数を見比べる。
rowspan のある表は、結合された下の行だけ値が少なくなる。
rowspan や入れ子の表、tbody より前の tfoot がある表は、上の toGrid のように table.rows と格子への配置で読むか、Python なら pandas.read_html を使う。ただし rowspan="0" はどちらのツールでも展開されないので、その表だけは自分で直す。
- 取り出した CSV を Markdown の表にするなら CSV⇄Markdown表 変換 が使える。
CSV の引用符が崩れたときの読まれ方は CSVの引用符1個で後ろの行が1セルに化ける理由と厳密パーサー、Markdown の表のセルに | を入れる方法は Markdown表のセルに|を入れる エスケープと実装差 も参考になる。
まとめ
- HTMLの表をCSVに変換は、
tr ごとに th / td を並べる。colspan は空セルで補うが、rowspan は展開しないので、結合された下の行が1列左へずれる。
querySelectorAll で行とセルを集めるため、入れ子の表の行やセルが外側の表に混ざる。tbody より前の tfoot はソースの順のまま出る。
<br> は textContent で消え、display:none の文字は値に残る。
- pandas の
read_html は rowspan / colspan をコピーして展開し、入れ子の表は別の表にし、tfoot を最後に置いた。rowspan="0" は展開しなかった。
table.rows と row.cells を使い、rowspan が埋めた位置を飛ばしながら格子に置くと、6つの表すべてで列がそろった。
結果は 2026-11-29 時点の上記の環境で得たものである。
参考
- HTML Living Standard「4.9 Tabular data」(
colspan / rowspan の範囲、rowspan="0"、HTMLTableElement.rows の順序、tfoot の位置)
- HTML 4.01 Specification「11.2.3 Row groups: the THEAD, TFOOT, and TBODY elements」(
tfoot を tbody の前に書く決まり)
- pandas ドキュメント
pandas.read_html(displayed_only、colspan / rowspan の扱い)
- jsdom 29.1.1、Node.js v24.11.1、pandas 3.1.1、lxml 6.2.0 での上記スクリプトによる実測
- ハシトシステム HTMLの表をCSVに変換のページのスクリプト(2026-11-29 確認)