概要
新しい JavaScript API v2 は、ジェネレーターの使用を廃止し async/await を採用することで、作業を簡素化することを目的としています。また、このAPIでは前バージョンのいくつかの制限が解消され、TypeScript のサポートが追加され、パフォーマンスが向上しました。すべての新しいスクレイパーの作成には、この JavaScript API を使用することをお勧めします。
JavaScript API v2 を使用するには、スクレイパークラスをベースの BaseParser から継承するだけで十分です。スクレイパークラスの構造を例で見てみましょう:
- TypeScript
- JavaScript
files/parsers/v2-example/v2-example.ts
import { BaseParser } from 'a-parser-types';
export class JS_v2_example extends BaseParser {
static defaultConf: typeof BaseParser.defaultConf = {
version: '0.0.1',
results: {
flat: [
['title', 'Title'],
['h1', 'H1 Header']
],
arrays: {
h2: ['H2 Headers List', [
['header', 'Header'],
]],
}
},
max_size: 2 * 1024 * 1024,
parsecodes: {
200: 1,
},
results_format: "Title: $title\nH1: $h1\nH2 headers:\n$h2.format('$header\\n')\n",
limitH2Tags: 3,
};
static editableConf: typeof BaseParser.editableConf = [
['limitH2Tags', ['textfield', 'Limit H2 tags']],
];
async parse(set, results) {
const { success, data, headers } = await this.request('GET', set.query);
if (success && typeof data == 'string') {
let matches;
if (matches = data.match(/<title[^>]*>(.*?)<\/title>/))
results.title = matches[1];
if (matches = data.match(/<h1[^>]*>(.*?)<\/h1>/))
results.h1 = matches[1];
if (results.h2) {
let count = 0;
const re = /<h2[^>]*>(.*?)<\/h2>/g;
while(matches = re.exec(data)) {
results.h2.push(matches[1]);
if (++count == this.conf.limitH2Tags)
break;
}
}
}
return results;
}
}
files/parsers/v2-example-js/v2-example-js.js
const { BaseParser } = require("a-parser-types");
class JS_v2_example_js extends BaseParser {
static defaultConf = {
version: '0.0.1',
results: {
flat: [
['title', 'Title'],
['h1', 'H1 Header']
],
arrays: {
h2: ['H2 Headers List', [
['header', 'Header'],
]],
}
},
max_size: 2 * 1024 * 1024,
parsecodes: {
200: 1,
},
results_format: "Title: $title\nH1: $h1\nH2 headers:\n$h2.format('$header\\n')\n",
limitH2Tags: 3,
};
static editableConf = [
['limitH2Tags', ['textfield', 'Limit H2 tags']],
];
async parse(set, results) {
const { success, data, headers } = await this.request('GET', set.query);
if (success && typeof data == 'string') {
let matches;
if (matches = data.match(/<title[^>]*>(.*?)<\/title>/))
results.title = matches[1];
if (matches = data.match(/<h1[^>]*>(.*?)<\/h1>/))
results.h1 = matches[1];
if (results.h2) {
let count = 0;
const re = /<h2[^>]*>(.*?)<\/h2>/g;
while(matches = re.exec(data)) {
results.h2.push(matches[1]);
if (++count == this.conf.limitH2Tags)
break;
}
}
}
return results;
}
}
TODO: (next) ## 継承
便利なリンク
🔗 ファイルをディスクに保存する例
ファイルをディスクに直接保存する方法を示す例
🔗 セッション操作の例
JavaScriptスクレイパーでのセッション機能の使用方法
🔗 セッションへのデータ保存の例
セッション内に任意のデータを保持する機能のデモンストレーション
🔗 results.addElement() の使用
results.addElement() を使用したデータ配列への入力例と、通常の .push() との違いのデモンストレーション