当我上传 html 文件时,Cheerio 不起作用



我正在使用以下函数,该函数在nodejs中实现express。我也在使用cheerio库进行一些网络抓取。下面的函数运行得很好,但这不是我想要的。我想直接上传文件,而不是像这样传递URL。

router.post('/transcript', async (req,res)=>{


const result = await request.get("https://www.codingwithstefan.com/table-example/");
const $ = cheerio.load(result);
$("body > table > tbody > tr > td").each((index, element) => {
console.log($(element).text());
});

});

我在使用cheerio时遇到了多个问题,我决定使用通话中的URL进行测试。网站已经不再是一张桌子了。现在我想做的是一样的,但不是像这样传递URL,而是直接上传我的HTML文件。我只需右键点击页面并保存为即可保存网站。我只需将网页的HTML文件保存在桌面上(名称为b.HTML(。现在我正在实现相同的功能,但我不需要像这样传递URL,而是使用以下curl命令curl -d "@C:/Users/yehya/Desktop/b.html" http://localhost:5000/api/transcript将HTML文件作为请求传递。函数几乎完全相同,但不是URL,而是cheerio.load((接收req.body。遗憾的是,这不起作用,我不明白为什么。该调用从不返回任何内容,我也尝试过使用它,但要么为null,要么未定义。我不明白为什么完全一样的东西不起作用。我猜当我上传这样的HTML文件时,会有一些变化,但我无法解决这里的问题。我已经盯着屏幕看了好几天了,非常感谢帮助。

router.post('/transcript', async (req,res)=>{


const $ = cheerio.load(req.body);
$("body > table > tbody > tr > td").each((index, element) => {
console.log($(element).text());
});

});

好吧,您在代码中做了一些错误的事情。这是一个列表:

  1. 您的代码没有用于处理文件上传的中间件。因此,这意味着您没有按预期传递HTML文件的内容。传递了一个空字符串,因此它不会生成表单元格的内容
  2. 你的卷发要求是错误的。对于文件上传,您需要使用-F标志

以下是我用您的代码和源文件测试的完整工作片段:

index.js

const express = require('express');
const bodyParser = require('body-parser');
const cheerio = require('cheerio');
const multer = require('multer');
const uploader = multer();
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', uploader.single('src'), async (req, res, nxt) => {
const src = req.file;
const content = src.buffer.toString('utf8');
const $ = cheerio.load(content);
$("body > table > tbody > tr > td").each((index, element) => {
console.log($(element).text());
});
//console.log(root);
res.json({ status: 200 });
});
app.listen(3000, () => {
console.log('App started');
});

您需要安装multerbody-parser才能使其工作(它可能在没有主体解析器的情况下工作,但处理其他POST请求时需要它(。您可以这样安装它们:npm i --save multer body-parser。在他们的npm/github页面上阅读更多关于multer和body解析器的信息。

其次,要上传文件,curl请求应该如下:

curl -X POST -F 'src=@/path/to/src-file.html' http://localhost:3000/

注意:传递给uploader中间件的名称srccurl上传文件时使用的名称相同。

最新更新