1.0.5 • Published 2 years ago
@imohuan/crawler v1.0.5
Crawler
文档在项目文件下的
docs
目录中
注意
- 爬虫功能不要滥用,不要多用
- 主要用于收集数据进行分析和学习使用
- 如存在违法情况,属于个人行为,将受到法律制裁
命令
im-crawler
快速根据配置文件进行爬虫获取
案例
im-crawler -c D:/config.js --start https://www.baidu.com/
// D:/config.js
const { resolve } = require("path");
module.exports = function () {
return {
dirname: resolve(__dirname, "datas"),
pages: [
{
name: "page英文名称",
description: "page描述",
matches: [
{
name: "测试配置",
description: "用于测试使用",
regexp: /.+/,
parsers: [{ name: "test", cls: "*{testVar}", print: true, replaces: [] }]
}
]
}
],
/** 配置插件, 不要参数的插件直接命名即可,带参数的插件使用数组, 自定义插件直接使用函数 */
plugins: ["CacheFsPlugin", "PrintPlugin"],
/** 全局变量 */
global: { testVar: "hello" }
};
};
electron-async
开启动态网页源码获取服务
功能
- 获取网络源码,并且支持
json
接口获取 - 利用
css选择器
解析HTML
并且增加自定义的选择器
方法,使用名称.
解析json
数据 - 可以通过
Crawler
类,配置爬虫数据,然后开启批量爬取网络数据 - 支持自定义插件开发,框架也提供了一些方便的插件
- 支持多进程
- 支持命令开启由
Electron
开发的可获取动态网络源码的服务
快速入门
- 安装依赖
pnpm i im-crawler -S
- 新建文件
test.ts
import { Crawler, StorePlugin, CacheFsPlugin, DownloadPlugin } from "im-crawler";
const crawler = new Crawler({
/** 数据缓存地址 */
dirname: resolve(__dirname, "datas2"),
/** spider配置 max 最大线程池 */
spider: { max: 2 },
/** 主要配置 存储爬虫的信息 */
pages: [
{
name: "bilibili",
description: "哔哩哔哩获取列表数据",
matches: [
{
name: "main-list",
/** 特殊请求获取 async 表示使用动态获取网页源码(需要开启动态服务 执行命令 `electron-async`) */
// request: { async: { show: true } },
regexp: /https\:\/\/www\.bilibili\.com.+/,
/** 将当前class选择器的链接进入下一次 start() 函数执行 */
areas: ["@.bili-header__banner a::attr(href)"],
/** StorePlugin 专属字段 */
// merger: "指定当前页面数据那一个字段应该保存进入数据库",
parsers: [
/** 每一个字段的获取*/
{ name: "title", cls: "title::text" },
{ name: "src", cls: "img::attr(src)" }
]
}
]
}
]
});
/** 使用插件 */
/** 将爬虫已经爬取的页面进行缓存,之后爬取相同的页面的时候就不需要再次请求 */
crawler.use(CacheFsPlugin);
/** 下载插件,使用默认下载器,还有aria2c下载器 */
crawler.use(DownloadPlugin("default"));
/** 为字段创建一个Sqlite数据库, 将爬取的数据存入数据库 */
crawler.use(StorePlugin());
/** 开始的URL - URL会进入所有的pages.matches列表中正则匹配该URL来确认应该使用哪一个配置*/
crawler.start("https://www.bilibili.com/");