dagongbao / headless.js
Your Name
1
cb3fcd8
raw
history blame contribute delete
No virus
5.72 kB
import puppeteer from 'puppeteer';
import tough from 'tough-cookie';
import iconv from 'iconv-lite';
import {load} from 'cheerio';
import path from 'path';
import fs from 'fs-extra';
import dotenv from 'dotenv';
import { execSync } from 'child_process';
import {join} from 'path';
import {jar, chineseToUnicode, downloadFile, gb2312UrlEncode, get, post, parseCookies, reset_cookie_jar} from './utils.js';
dotenv.config();
const host = 'https://mmis.hkpl.gov.hk'
async function get_list(page) {
const url = `${host}/search-result?p_p_id=search_WAR_mmisportalportlet&p_p_lifecycle=0&p_p_state=normal&_search_WAR_mmisportalportlet_keywords=%E5%A4%A7%E5%85%AC%E5%A0%B1&_search_WAR_mmisportalportlet_hsf=%E5%A4%A7%E5%85%AC%E5%A0%B1&p_r_p_-1078056564_actual_q=%28%20all_dc.title%3A%28%22%E5%A4%A7%E5%85%AC%E5%A0%B1%22%29%29%20AND+%28%20verbatim_dc.collection%3A%28%22Old%5C%20HK%5C%20Newspapers%22%29%29&p_r_p_-1078056564_sort_field=dc.publicationdate_bsort&_search_WAR_mmisportalportlet_mode=Advanced&p_r_p_-1078056564_curr_page=${page}&_search_WAR_mmisportalportlet__advancedsearch_WAR_mmisportalportlet_formDate=1389840730864&p_r_p_-1078056564_new_search=false&p_r_p_-1078056564_sort_order=desc&_search_WAR_mmisportalportlet_jspPage=%2Fjsp%2Fsearch%2Fcnsc05.jsp`;
let html = "";
const dir = `./html/list`;
const f = join(dir, page + ".html");
if (
await fs.exists(f) &&
(await fs
.readFile(f))
.toString()
.indexOf("The system is busy. Please retry later") != -1
) {
await fs.unlink(f);
}
if (await fs.exists(f)) {
console.log("exists", f);
html = (await fs.readFile(f)).toString();
} else {
while (true) {
const { data } = await get(url);
if (data.indexOf("The system is busy. Please retry later") != -1) {
continue;
}
html = data;
const a = html.indexOf("<body");
const b = html.indexOf("</body>");
html = html.substring(a, b) + "</body>";
const links = load(html)(".result-title a");
await fs.ensureDir(dir);
if (!links.length) {
return [];
}
await fs.writeFile(f, html);
break;
}
}
const links = load(html)(".result-title a");
const res = [];
for (const link of links) {
res.push({
href: link.attribs.href,
text: link.children[0].data,
});
}
return res;
}
async function crawl_by_page(page) {
const links = await get_list(page);
for (const link of links) {
const date_str = link.text.split(" ")[1];
let [year, month, day] = date_str.split("-");
month = parseInt(month);
day = parseInt(day);
year = parseInt(year);
const dir = join(`./html/newspaper/${year}/${month}/${day}`);
const f = join(dir, "index.html");
let detail_html = "";
if ((await fs.exists(f)) && (await fs.readFile(f)).toString().indexOf('The system is busy. Please retry later') != -1) {
await fs.unlink(f);
}
if (await fs.exists(f)) {
console.log("exists", f);
detail_html = (await fs.readFile(f)).toString();
} else {
await fs.ensureDir(dir);
while (true) {
const { data: html } = await get(`${host}${link.href}`);
if (html.indexOf("The system is busy. Please retry later") != -1) continue;
await fs.writeFile(f, html);
detail_html = html;
break;
}
}
const key = 'htmlURL="';
const pivot = detail_html.indexOf(key);
const viewer_url = `${host}${detail_html.substring(
pivot + key.length,
detail_html.indexOf('"', pivot + key.length)
)}`;
const key2 = "initPageLinks(null,";
const pivot2 = detail_html.indexOf(key2);
const total_page = parseInt(
detail_html.substring(
pivot2 + key2.length,
detail_html.indexOf(",", pivot2 + key2.length)
)
);
const search_params = new URLSearchParams("?" + viewer_url.split("?")[1]);
const month_pad_start = month.toString().padStart(2, "0");
const day_pad_start = day.toString().padStart(2, "0");
for (let i = 1; i <= total_page; ++i) {
// console.log("download img", year, month, day, i, "/", total_page);
const img_path = join(dir, i + ".png");
if (await fs.exists(img_path)) {
if ((await fs.readFile(img_path)).toString().indexOf('The system is busy. Please retry later') != -1) {
await fs.unlink(img_path);
} else {
// console.log("skip");
continue;
}
}
// const encToken = search_params.get("encToken");
const encToken =
'...';
const img_url =
`https://mmis.hkpl.gov.hk/ebook/viewer?resource=page` +
`&item=${search_params.get("item")}` +
`&type=` +
`&ref=%2FMULTI_IMAGE_INDEX%2F${
month_pad_start + day_pad_start
}%2FNPTKP${
year.toString() + month_pad_start + day_pad_start
}%2Fimage%2FNPTKP${
year.toString() + month_pad_start + day_pad_start
}_${i.toString().padStart(2, "0")}.png` +
`&encToken=${encodeURIComponent(encToken)}`;
// console.log(img_url);
await downloadFile(img_url, img_path, Infinity);
}
// const {data: viewer_html} = await get(viewer_url);
// console.log(viewer_html);
// return;
}
}
(async () => {
const pages = Math.floor(16865 / 10);
const arr = (new Array(pages)).fill(0).map((_, i) => i+1);//.sort(() => Math.random() > 0.5 ? 1 : -1);
/*
for (let i = 1; i <= pages; ++i) {
// console.log(i + "/" + pages);
crawl_by_page(i);
}
*/
await Promise.all[
new Array(10).fill(0).map(async (i) => {
while (arr.length) {
console.log(arr.length);
await crawl_by_page(arr.pop());
}
})
];
})();