Library to make parsing website tables much easier!
When you are using puppeteer for scrapping websites and web application, you will find out that parsing tables consistently is not that easy.
This library brings you abstraction between puppeteer and page context.
- β¨ Parsing columns by their name.
- β¨ Respect the defined order of columns.
- β¨ Appending custom columns with custom data.
- β¨ Custom sanitization of data in cells.
- β¨ Group and Aggregate data by your own function.
- β¨ Merge data from two independent tables into one structure.
- β¨ Handles invalid HTML structure.
- β¨ Retrieve results as CSV or array of plain JS objects.
- β¨ And much more!
yarn add puppeteer-table-parsernpm install puppeteer-table-parser// CommonJS
const { tableParser } = require('puppeteer-table-parser')
// ESM / Typescript
import { tableParser } from 'puppeteer-table-parser'interface ParserSettings {
selector: string; // CSS selector
allowedColNames: Record<string, string>; // key = input name, value = output name)
headerRowsSelector?: string | null; // (default: 'thead tr', null ignores table's header selection)
headerRowsCellSelector?: string; // (default: 'td,th')
bodyRowsSelector?: string; // (default: 'tbody tr')
bodyRowsCellSelector?: string; // (default: 'td')
cellTextSource?: CellTextSource; // (default: 'innerText') see "Cell text source" below
reverseTraversal?: boolean // (default: false)
temporaryColNames?: string[]; // (default: [])
extraCols?: ExtraCol[]; // (default: [])
withHeader?: boolean; // (default: true)
csvSeparator?: string; // (default: ';')
newLine?: string; // (default: '\n')
rowValidationPolicy?: RowValidationPolicy; // (default: 'NON_EMPTY')
groupBy?: {
cols: string[];
handler?: (rows: string[][], getColumnIndex: GetColumnIndexType) => string[];
}
rowValidator: (
row: string[],
getColumnIndex: GetColumnIndexType,
rowIndex: number,
rows: Readonly<string[][]>,
) => boolean;
rowTransform?: (row: string[], getColumnIndex: GetColumnIndexType) => void;
asArray?: boolean; // (default: false)
rowValuesAsArray?: boolean; // (default: false)
rowValuesAsObject?: boolean; // (default: false)
colFilter?: (elText: string[], index: number) => string; // (default: (txt: string) => txt.join(' '))
colParser?: (value: string, formattedIndex: number, getColumnIndex: GetColumnIndexType) => string; // (default: (txt: string) => txt.trim())
optionalColNames?: string[]; // (default: [])
excludedColumns?: (rows: string[][], getColumnIndex: GetColumnIndexType) => string[]; // (default: undefined)
};- Find table(s) by provided CSS selector.
- Find associated columns by applying
colFilteron their text and verify their count. - Filter rows based on
rowValidationPolicy - Add extra columns specified in
extraColsproperty in settings. - Run
rowValidatorfunction for every table row. - Run
colParserfor every cell in a row. - Run
rowTransformfunction for each row. - Group results into buckets (
groupBy.cols) property and pick the aggregated rows. - Add processed row to a temp array result.
- Run
excludedColumnsand exclude retrieved columns from the rows and theheader. - Add
headerrow (ifwithHeaderproperty istrue). - Merge partial results and return them.
By default each body cell is read with HTMLElement.innerText. innerText
reflects the rendered text, but reading it forces the browser to perform a
synchronous layout/reflow for every cell β which dominates parse time on large
tables.
Setting cellTextSource: CellTextSource.TEXT_CONTENT switches the body-cell read
to Node.textContent, which does not trigger layout. On large tables this is
substantially faster (measured ~15β40% lower parse time on a 35 000 Γ 12 table,
~22% median), with identical output on whitespace-clean tables.
import { tableParser, CellTextSource } from 'puppeteer-table-parser'
await tableParser(page, {
selector: 'table',
allowedColNames: { 'Car Name': 'car' },
cellTextSource: CellTextSource.TEXT_CONTENT, // faster; see caveats below
})When output can differ.
textContentreturns the raw source text, so it diverges frominnerTexton three cases (all of which survive the default.trim()colParser):
- Interior whitespace runs β
innerTextcollapsesfoo bartofoo bar;textContentpreserves the run.<br>elements βinnerTextrenders them as a newline;textContentemits nothing.display:nonedescendants βinnerTextomits hidden text;textContentincludes it.Keep the default
innerTextif your cells contain any of the above and you rely on the rendered representation. For the common case of plain-text data cells,textContentis a safe, faster drop-in.
All data came from the HTML page, which you can find in
test/assets/1.html.
Basic example (the simple table where we want to parse three columns without editing)
import { tableParser } from 'puppeteer-table-parser'
await tableParser(page, {
selector: 'table',
allowedColNames: {
'Car Name': 'car',
'Horse Powers': 'hp',
'Manufacture Year': 'year',
},
});car;hp;year
Audi S5;332;2015
Alfa Romeo Giulia;500;2020
BMW X3;215;2017
Skoda Octavia;120;2012Basic example with custom column name parsing:
import { tableParser } from 'puppeteer-table-parser'
await tableParser(page, {
selector: 'table',
colFilter: (value: string[]) => {
return value.join(' ').replace(' ', '-').toLowerCase();
},
colParser: (value: string) => {
return value.trim();
},
allowedColNames: {
'car-name': 'car',
'horse-powers': 'hp',
'manufacture-year': 'year',
},
})car;hp;year
Audi S5;332;2015
Alfa Romeo Giulia;500;2020
BMW X3;215;2017
Skoda Octavia;120;2012Basic example with row validation and using temporary column.
import { tableParser } from 'puppeteer-table-parser'
await tableParser(page, {
selector: 'table',
allowedColNames: {
'Car Name': 'car',
'Manufacture Year': 'year',
'Horse Powers': 'hp',
},
temporaryColNames: ['Horse Powers'],
rowValidator: (row: string[], getColumnIndex) => {
const powerIndex = getColumnIndex('hp');
return Number(row[powerIndex]) < 250;
},
});car;year
BMW X3;2017
Skoda Octavia;2012Advanced example:
Uses custom temporary column for filtering. It uses an extra column with custom position to be filled on a fly.
import { tableParser } from 'puppeteer-table-parser'
await tableParser(page, {
selector: 'table',
allowedColNames: {
'Manufacture Year': 'year',
'Horse Powers': 'hp',
'Car Name': 'car',
},
temporaryColNames: ['Horse Powers'],
extraCols: [
{
colName: 'favorite',
data: '',
position: 0,
},
],
rowValidator: (row: string[], getColumnIndex) => {
const horsePowerIndex = getColumnIndex('hp');
return Number(row[horsePowerIndex]) > 150;
},
rowTransform: (row: string[], getColumnIndex) => {
const nameIndex = getColumnIndex('car');
const favoriteIndex = getColumnIndex('favorite');
if (row[nameIndex].includes('Alfa Romeo')) {
row[favoriteIndex] = 'YES';
} else {
row[favoriteIndex] = 'NO';
}
},
asArray: false,
rowValuesAsArray: false
});favorite;year;car
NO;2015;Audi S5
YES;2020;Alfa Romeo Giulia
NO;2017;BMW X3Optional columns
Sometimes you can be in a situation where some if
your columns are desired, but they are not available in a table.
You can easily add an exception for them via optionalColNames property.
import { tableParser } from 'puppeteer-table-parser'
await tableParser(page, {
selector: 'table',
allowedColNames: {
'Car Name': 'car',
'Rating': 'rating',
},
optionalColNames: ['rating']
});Grouping and Aggregating
import { tableParser } from 'puppeteer-table-parser'
await tableParser(page, {
selector: '#my-table',
allowedColNames: {
'Employee Name': 'name',
'Age': 'age',
},
groupBy: {
cols: ['name'],
handler: (rows: string[][], getColumnIndex) => {
const ageIndex = getColumnIndex('age');
// select one with the minimal age
return rows.reduce((previous, current) =>
previous[ageIndex] < current[ageIndex] ? previous : current,
);
},
}
});For more, look at the test folder! π