--[[--
轻量 HTML DOM:解析、序列化、取文本,以及 Legado 的 HtmlFormatter(正文清洗)。
节点:{type="el", tag, attrs, attrOrder, children, parent, order} / {type="text", text, parent, order} /
根 {type="doc"}。标签与属性名小写。
@module moonsource_legadorule.html
--]]
local Html = {}
local NAMED = {
nbsp = "\194\160", amp = "&", lt = "<", gt = ">", quot = '"', apos = "'", copy = "©", reg = "®",
hellip = "…", mdash = "—", ndash = "–", ldquo = "“", rdquo = "”", lsquo = "‘", rsquo = "’",
middot = "·", times = "×", divide = "÷", laquo = "«", raquo = "»", bull = "•", trade = "™",
yen = "¥", pound = "£", euro = "€", cent = "¢", sect = "§", deg = "°", ensp = "\226\128\130",
emsp = "\226\128\131", thinsp = "\226\128\137", zwnj = "\226\128\140", zwj = "\226\128\141",
}
local function utf8(cp)
if cp < 0x80 then return string.char(cp) end
if cp < 0x800 then return string.char(0xC0 + math.floor(cp / 64), 0x80 + cp % 64) end
if cp < 0x10000 then
return string.char(0xE0 + math.floor(cp / 0x1000), 0x80 + math.floor(cp / 64) % 64, 0x80 + cp % 64)
end
return string.char(0xF0 + math.floor(cp / 0x40000), 0x80 + math.floor(cp / 0x1000) % 64,
0x80 + math.floor(cp / 64) % 64, 0x80 + cp % 64)
end
--- 解 HTML 实体。
function Html.decode(s)
if not s:find("&", 1, true) then return s end
return (s:gsub("&(#?[%w]+);?", function(name)
local whole = name
if name:sub(1, 1) == "#" then
local cp = name:sub(2, 2):lower() == "x" and tonumber(name:sub(3), 16) or tonumber(name:sub(2))
if cp and cp > 0 and cp < 0x110000 then return utf8(cp) end
return nil
end
return NAMED[whole] or NAMED[whole:lower()]
end))
end
local VOID = {
area = 1, base = 1, br = 1, col = 1, embed = 1, hr = 1, img = 1, input = 1, link = 1, meta = 1,
param = 1, source = 1, track = 1, wbr = 1,
}
local RAW = { script = 1, style = 1, textarea = 1, title = 1 }
local BLOCK = {
address = 1, article = 1, aside = 1, blockquote = 1, body = 1, br = 1, dd = 1, div = 1, dl = 1, dt = 1,
fieldset = 1, figure = 1, footer = 1, form = 1, h1 = 1, h2 = 1, h3 = 1, h4 = 1, h5 = 1, h6 = 1,
header = 1, hr = 1, li = 1, main = 1, nav = 1, ol = 1, p = 1, pre = 1, section = 1, table = 1, tbody = 1,
td = 1, th = 1, thead = 1, tr = 1, ul = 1,
}
Html.VOID, Html.BLOCK = VOID, BLOCK
-- 新开标签 → 需要先隐式关闭的同级标签
local CLOSES = {
li = { li = 1 }, dt = { dt = 1, dd = 1 }, dd = { dt = 1, dd = 1 }, option = { option = 1 },
td = { td = 1, th = 1 }, th = { td = 1, th = 1 }, tr = { tr = 1, td = 1, th = 1 },
thead = { tbody = 1, tfoot = 1 }, tbody = { thead = 1, tbody = 1, tfoot = 1, tr = 1, td = 1, th = 1 },
}
for tag in pairs(BLOCK) do
if tag ~= "br" and tag ~= "hr" and tag ~= "td" and tag ~= "th" and tag ~= "tr" and tag ~= "li" then
CLOSES[tag] = CLOSES[tag] or {}
CLOSES[tag].p = 1
end
end
local SCOPE = {
ul = 1, ol = 1, table = 1, div = 1, td = 1, th = 1, section = 1, article = 1, body = 1, html = 1,
blockquote = 1, dl = 1, form = 1, main = 1, nav = 1, header = 1, footer = 1, aside = 1,
}
local function parseAttrs(src)
local attrs, list = {}, {}
local i = 1
while true do
local s, e, name = src:find("^[%s/]*([^%s=/>]+)", i)
if not s then break end
i = e + 1
local value = ""
local s2, e2 = src:find("^%s*=%s*", i)
if s2 then
i = e2 + 1
local q = src:sub(i, i)
if q == '"' or q == "'" then
local close = src:find(q, i + 1, true) or #src + 1
value = src:sub(i + 1, close - 1)
i = close + 1
else
value = src:match("^[^%s>]*", i)
i = i + #value
end
end
name = name:lower()
if attrs[name] == nil then
list[#list + 1] = name
attrs[name] = Html.decode(value)
end
end
return attrs, list
end
--- 解析 HTML 片段 / 文档,返回根节点。
function Html.parse(src)
local root = { type = "doc", children = {}, order = 0 }
local stack, top, order = { root }, root, 0
local function add(node)
order = order + 1
node.order, node.parent = order, top
top.children[#top.children + 1] = node
end
local i, len = 1, #src
while i <= len do
local lt = src:find("<", i, true)
if not lt then
add({ type = "text", text = Html.decode(src:sub(i)) })
break
end
if lt > i then add({ type = "text", text = Html.decode(src:sub(i, lt - 1)) }) end
if src:sub(lt, lt + 3) == "", lt + 4, true)
i = (e or len) + 1
elseif src:sub(lt, lt + 1) == "", lt, true) or len) + 1
elseif src:sub(lt, lt + 1) == "" then
local gt = src:find(">", lt, true) or len
local tag = src:match("^%s*([%w:_-]+)", lt)
i = gt + 1
if tag then
tag = tag:lower()
for k = #stack, 2, -1 do
if stack[k].tag == tag then
for _ = k, #stack do stack[#stack] = nil end
top = stack[#stack]
break
end
end
end
else
local tag = src:match("^<([%a][%w:_-]*)", lt)
if not tag then
add({ type = "text", text = "<" })
i = lt + 1
else
tag = tag:lower()
-- 找到不在引号里的 >
local j, q = lt + 1 + #tag, nil
while j <= len do
local c = src:sub(j, j)
if q then
if c == q then q = nil end
elseif c == '"' or c == "'" then
q = c
elseif c == ">" then
break
end
j = j + 1
end
local inner = src:sub(lt + 1 + #tag, j - 1)
local selfClose = inner:sub(-1) == "/"
local attrs, list = parseAttrs(inner)
i = j + 1
local closes = CLOSES[tag]
if closes then
local found
for k = #stack, 2, -1 do
local t = stack[k].tag
if closes[t] then
found = k
elseif SCOPE[t] then
break
end
end
if found then
for _ = found, #stack do stack[#stack] = nil end
top = stack[#stack]
end
end
local node = { type = "el", tag = tag, attrs = attrs, attrOrder = list, children = {} }
add(node)
if RAW[tag] and not selfClose then
local s, e = src:lower():find("" .. tag .. "%s*>", i)
local body = src:sub(i, (s or len + 1) - 1)
if body ~= "" then
order = order + 1
local raw = tag == "script" or tag == "style"
local t = { type = "text", text = raw and body or Html.decode(body),
order = order, parent = node, raw = raw }
node.children[1] = t
end
i = (e or len) + 1
elseif not VOID[tag] and not selfClose then
stack[#stack + 1] = node
top = node
end
end
end
end
return root
end
---------------------------------------------------------------- 序列化与取文本
local function escapeText(s)
return (s:gsub("[&<>\194]", function(c)
if c == "&" then return "&" end
if c == "<" then return "<" end
if c == ">" then return ">" end
return c
end):gsub("\194\160", " "))
end
local function escapeAttr(s)
return (s:gsub('[&"]', { ["&"] = "&", ['"'] = """ }))
end
local function serialize(node, out)
if node.type == "text" then
out[#out + 1] = node.raw and node.text or escapeText(node.text)
elseif node.type == "el" then
out[#out + 1] = "<" .. node.tag
for _, name in ipairs(node.attrOrder) do
out[#out + 1] = " " .. name .. '="' .. escapeAttr(node.attrs[name]) .. '"'
end
out[#out + 1] = ">"
if not VOID[node.tag] then
for _, c in ipairs(node.children) do serialize(c, out) end
out[#out + 1] = "" .. node.tag .. ">"
end
else
for _, c in ipairs(node.children) do serialize(c, out) end
end
end
function Html.outer(node)
local out = {}
serialize(node, out)
return table.concat(out)
end
function Html.inner(node)
local out = {}
for _, c in ipairs(node.children or {}) do serialize(c, out) end
return table.concat(out)
end
local function collect(node, out)
if node.type == "text" then
if not node.raw then out[#out + 1] = node.text end
elseif node.type == "el" then
local block = BLOCK[node.tag]
if block then out[#out + 1] = " " end
for _, c in ipairs(node.children) do collect(c, out) end
if block then out[#out + 1] = " " end
else
for _, c in ipairs(node.children) do collect(c, out) end
end
end
local function collapse(s)
s = s:gsub("[ \t\r\n\f]+", " ")
return (s:gsub("^ ", ""):gsub(" $", ""))
end
Html.collapse = collapse
--- jsoup text():连续空白折叠、块级元素之间留空格。
function Html.text(node)
local out = {}
collect(node, out)
return collapse(table.concat(out))
end
--- 不含子元素的自有文本(jsoup ownText)。
function Html.ownText(node)
local out = {}
for _, c in ipairs(node.children or {}) do
if c.type == "text" and not c.raw then out[#out + 1] = c.text end
end
return collapse(table.concat(out))
end
--- Legado textNodes:每个直接文本节点修剪后按行拼接。
function Html.textNodes(node)
local out = {}
for _, c in ipairs(node.children or {}) do
if c.type == "text" and not c.raw then
local t = collapse(c.text)
if t ~= "" then out[#out + 1] = t end
end
end
return table.concat(out, "\n")
end
--- 原样拼接的文本内容(XPath string-value)。
function Html.textContent(node)
if node.type == "text" then return node.text end
local out = {}
local function walk(n)
for _, c in ipairs(n.children or {}) do
if c.type == "text" then out[#out + 1] = c.text else walk(c) end
end
end
walk(node)
return table.concat(out)
end
--- Legado `html`:去掉 script / style 的 innerHTML。
function Html.cleanInner(node)
local out = {}
local function walk(n)
if n.type == "el" and (n.tag == "script" or n.tag == "style") then return end
serialize(n, out)
end
for _, c in ipairs(node.children or {}) do walk(c) end
return table.concat(out)
end
---------------------------------------------------------------- HtmlFormatter
local function lines(s)
local out = {}
for line in (s .. "\n"):gmatch("(.-)\r?\n") do
line = line:gsub("^[%s\194\160\227\128\128]+", ""):gsub("[%s\194\160\227\128\128]+$", "")
if line ~= "" then out[#out + 1] = line end
end
return table.concat(out, "\n")
end
local function stripBlocks(s)
s = s:gsub("<[sS][cC][rR][iI][pP][tT].-[sS][cC][rR][iI][pP][tT]>", "")
s = s:gsub("<[sS][tT][yY][lL][eE].-[sS][tT][yY][lL][eE]>", "")
return (s:gsub("", ""))
end
local function breaks(s)
s = s:gsub("<[bB][rR]%s*/?>", "\n"):gsub("<[hH][rR]%s*/?>", "\n")
s = s:gsub("[pP]>", "\n"):gsub("[dD][iI][vV]>", "\n"):gsub("[lL][iI]>", "\n")
s = s:gsub("[tT][rR]>", "\n"):gsub("[hH][1-6]>", "\n")
return (s:gsub("<[pP][%s>]", "\n%0"))
end
--- 取纯文本:块级换行、去标签、解实体、逐行修剪。
function Html.format(s)
if not s or s == "" then return "" end
s = breaks(stripBlocks(s)):gsub("<[^>]*>", "")
return lines(Html.decode(s))
end
local IMG_ATTRS = { "src", "data-src", "data-original", "data-lazy-src" }
--- 同 format,但保留图片:
,纯图片 URL 也包成
。base 用来补全相对地址。
function Html.formatKeepImg(s, absolute, base)
if not s or s == "" then return "" end
s = breaks(stripBlocks(s))
s = s:gsub("<[iI][mM][gG]([^>]*)>", function(attrs)
local a = parseAttrs(attrs)
for _, name in ipairs(IMG_ATTRS) do
local v = a[name]
if v and v ~= "" then
if absolute then v = absolute(base, v) end
return '\n
\n'
end
end
return ""
end)
local imgs = {}
s = s:gsub('
', function(tag)
imgs[#imgs + 1] = tag
return "\1" .. #imgs .. "\1"
end)
s = s:gsub("<[^>]*>", "")
s = lines(Html.decode(s))
s = s:gsub("\1(%d+)\1", function(n) return imgs[tonumber(n)] end)
return s
end
return Html