【问题标题】:Cheerio Doesn't work when I upload an html file当我上传 html 文件时 Cheerio 不起作用
【发布时间】:2020-11-15 13:04:27
【问题描述】:

我正在使用以下在 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 文件作为请求传递。该函数几乎完全相同,但在 req.body 中,cheerio.load() 不是 URL。可悲的是,这不起作用,我不明白为什么。该调用从不返回任何内容,我也尝试过使用它,但要么得到 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());
  });
  
});

【问题讨论】:

  • 您是如何尝试加载文件的? fs.readFileSync?读取文件时是否添加了utf8 的编码?
  • var fs = require('fs');我所做的一切都是为了加载 fs

标签: node.js express cheerio


【解决方案1】:

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

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

这是我用你的代码和源文件测试的完整的工作 sn-p:

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-parser 的信息。

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

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

注意一件事:传递给uploader中间件的名称,src与用于上传文件的名称与curl相同。

【讨论】:

    猜你喜欢
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 2012-04-01
    • 2014-08-08
    相关资源
    最近更新 更多