1 Star 0 Fork 3

lebu9527/puppeteer+koa爬虫程序

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
service.js 1.41 KB
一键复制 编辑 原始数据 按行查看 历史
钟鹏 提交于 2024-08-17 10:36 +08:00 . feat: 创建爬虫程序
const Koa = require("koa");
const Router = require("koa-router");
const minify = require('html-minifier').minify;
const spider = require("./spider.js");
const requestLog = require("./request-log.js");
const app = new Koa();
const router = new Router();
// 记录请求次数
let reqTimes = 0
router.get(/.*/, async (ctx) => {
reqTimes += 1
// 记录请求日志
requestLog(ctx.request, 'request.log', reqTimes)
const url = "https://www.baidu.com" + ctx.originalUrl; // 目标网站URL
try {
let content = ''
const { html = '获取html内容失败', contentType } = await spider(url)
// 通过minify库压缩代码
content = minify(html, { removeComments: true, collapseWhitespace: true, minifyJS: true, minifyCSS: true });
if (ctx.request.url.indexOf(".") < 0) {
ctx.set("Content-Type", "text/html");
} else {
ctx.set("Content-Type", contentType);
}
ctx.body = content; // 将HTML代码返回给前端
} catch (error) {
const errorObject = {
message: error.message,
name: error.name,
stack: error.stack
};
// 记录错误日志
requestLog(errorObject, 'error.log')
ctx.body = '获取html内容失败';
}
})
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000, () => {
console.log("服务已启动在3000端口...");
});
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/lebu2018/puppeteer_koa.git
git@gitee.com:lebu2018/puppeteer_koa.git
lebu2018
puppeteer_koa
puppeteer+koa爬虫程序
master

搜索帮助