File size: 5,470 Bytes
5769ed9 |
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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
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%B7%A5%E5%95%86%E6%99%9A%E5%A0%B1&_search_WAR_mmisportalportlet_hsf=%E5%B7%A5%E5%95%86%E6%99%9A%E5%A0%B1&p_r_p_-1078056564_actual_q=%28%20all_dc.title%3A%28%22%E5%B7%A5%E5%95%86%E6%99%9A%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_formDate=1448775486359&_search_WAR_mmisportalportlet_mode=Advanced&p_r_p_-1078056564_curr_page=${page}&p_r_p_-1078056564_new_search=true&p_r_p_-1078056564_sort_order=desc&p_r_p_-1078056564_filter=&_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)) {
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>";
await fs.writeFile(f, html);
break;
}
}
const links = load(html)(".result-title a");
const inputs = load(html)(".aui-button-input.mmis-button-full");
await fs.ensureDir(dir);
const res = [];
let x = 0;
for (const link of links) {
res.push({
href: link.attribs.href,
text: link.children[0].data,
id: inputs[x].attribs.onclick.split('ITEM_ID=')[1].split('&')[0],
});
++x;
}
return res;
}
function page_transform(year, month, day, page) {
if (year == 1984 && month == 10 && day == 9 && page == 12)
return page.toString().padStart(3, "0")
return page.toString().padStart(2, "0")
}
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)) {
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]);
// fid may mismatch year_month_day. fid is correct.
const fid = detail_html.substring(detail_html.indexOf('Bib ID')).split('value-content " > <span>')[1].split('<')[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)) {
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")}` +
// `&item=${link.id}` +
`&type=` +
`&ref=%2FMULTI_IMAGE_INDEX%2F${
fid.substring(fid.length - 4)
}%2F${
fid
}%2Fimage%2F${
fid
}_${
page_transform(year, month, day, i)
}.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(16191 / 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());
}
})
];
})();
|