migrate-lsw/ministry-laws-regulations.js
2026-01-13 10:17:00 +07:00

99 lines
2.9 KiB
JavaScript

// กฎหมาย ระเบียบ และประกาศกระทรวง
const { execSync } = require("child_process");
const cheerio = require("cheerio");
const fs = require("fs");
const path = require("path");
const BASE = "https://ladsawai.go.th";
const OUT = path.join(process.cwd(), "กฎหมาย ระเบียบ และประกาศกระทรวง");
fs.mkdirSync(OUT, { recursive: true });
function curlHtml(url) {
return execSync(
`curl -L -s "${url}" -H "User-Agent: Mozilla/5.0" -H "Accept-Language: th-TH,th;q=0.9"`,
{ encoding: "utf8", maxBuffer: 30 * 1024 * 1024 }
);
}
function absUrl(href) {
if (!href) return null;
if (href.startsWith("http")) return href; // ลิงก์นอกโดเมน
if (href.startsWith("/")) return BASE + href; // /public/...
return BASE + "/" + href; // public/...
}
function scrapeLawMenu(menuId) {
const url = `${BASE}/rss/data/rules/menu/${menuId}`;
const html = curlHtml(url);
// debug
fs.writeFileSync(path.join(OUT, `debug-menu-${menuId}.html`), html, "utf8");
const $ = cheerio.load(html);
const items = [];
// ในรูปอยู่ใน table > tbody > tr และข้อมูลอยู่ที่ td.rules-topic
$("table tbody tr").each((_, tr) => {
const tds = $(tr).find("td.rules-topic");
if (tds.length < 2) return;
// ✅ ช่องที่ 2 คือข้อมูลจริง
const td = tds.eq(1);
// title ที่ถูกต้องมักอยู่ใน <a> ตัวที่เป็นข้อความยาว (มักเป็นตัวสุดท้าย)
const title = td.find("a[href]").last().text().replace(/\s+/g, " ").trim();
if (!title || title === "-") return;
// เก็บ link ทุกตัวใน td (มีทั้ง read + download)
const links = [];
td.find("a[href]").each((_, a) => {
const href = $(a).attr("href");
const text = $(a).text().replace(/\s+/g, " ").trim();
links.push({
text: text || null,
href: absUrl(href),
});
});
const detail =
td
.clone()
.find("a") // ตัด a ออก เหลือ text ล้วน
.remove()
.end()
.text()
.replace(/\s+/g, " ")
.trim() || null;
items.push({
title,
detail,
links,
sourceUrl: url,
});
});
return { url, items };
}
(function main() {
const menuId = 1221;
const { url, items } = scrapeLawMenu(menuId);
const out = {
menuId,
source: url,
scrapedAt: new Date().toISOString(),
totalItems: items.length,
items,
};
const outJson = path.join(OUT, `menu-${menuId}-all.json`);
fs.writeFileSync(outJson, JSON.stringify(out, null, 2), "utf8");
console.log("✅ Saved:", outJson);
console.log("✅ Items:", items.length);
})();