需求
我想获取当前访问页面的table中的数据,然后存储文文本或excel文件
借助工具
- tabletojson
- xlsx
- 或者手动爬取HTML文档,然后借助jQuery等工具手动解析文档
tabletojson
INTRO:尝试将HTML tables转换为JSON。
RETURN:始终返回一个数组,长度根据html中的table数量决定
注意:
- 如果table列中存在重复的列名,会给后面的列名加上数字后缀,如: xxxx_2
- 如果存在合并行rowspan,会被自动解除合并,恢复原始数据
- 表格的第一行是标题,useFirstRowForHeadings:true
- table中包含了html元素等等,默认情况下,将会将所有的内容转换为纯文本----也就是解析过的不含标签的,使得到对象会更简单。可配置项:stripHtmlFromHeadings、stripHtmlFromCells,如果要同时设置前面两项,可以设置stripHtml
- convertUrl可以设置代理,依赖got–一个最好用的nodejs平台的HTTP请求库
平台:nodejs
const tabletojson = require('tabletojson').Tabletojson
const fs = require('fs')
const path = require('path')
// tunnel包已经无人维护了,但仍然很受欢迎【一个用于隧道代理的 HTTP/HTTPS 代理】
const tunnel = require('tunnel')
// 解析远程页面
tabletojson.convertUrl(
'https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes',
{
// 可选的配置项
useFirstRowForHeadings: true, // 第一行为标题,那就忽略掉【默认值为true】
stripHtmlFromCells: true, // 默认值:true
stripHtmlFromHeadings: true, // 默认值:true
forceIndexAsNumber: false, // 强制使用index作为标题,而不是列名
countDuplicateHeadings: true, // 重复标题默认会加数字后缀
ignoreColumns: [1,3], // 忽略列索引为1,3的列
onlyColumns: [1,3], // 只显示索引为1,3的列
ignoreHiddenRows: true, // 忽略设置为display:none的行
headings: ['A'], // 默认值null/undefined, 重命名表格列名
limitrows: 20, // null/undefined,限制行数
containsClasses: [], //null/undefined, 限定查找使用了指定class的table
got: { // 只能用于这个convertUrl中,设置proxy\headers
agent: tunnel.httpOverHttp({
proxy: {
host: 'proxy:8080'
}
})
}
}
(tableasjson) => {
console.log(tableasjson)
})
// 解析已有的html文件
const fileHtml = fs.readFileSync(path.resolve(__dirname, '../demo.html'))
const tableData = tabletojson.conver(fileHtml)
console.log(tableData)