【问题标题】:node-fetch to get id from html website but I am getting error 200 undefinednode-fetch 从 html 网站获取 id 但我收到错误 200 undefined
【发布时间】:2021-10-16 20:59:34
【问题描述】:

我刚开始学习 Node.js。

我正在尝试使用 node-fetch 返回响应的正文,但我收到了未定义的输出。我应该得到一个 '0' 作为响应,但我得到的是 '200 undefined'

这是来自我试图获取“0”的目标网站

<td id="pendingBlocks" style="text-align:center;vertical-align: middle;">0</td>

这是脚本。

const fetch = require("node-fetch");
async function getCourseCode() {
    try {
        let response = await fetch('https://websitehere');
        let body = await response.text();
        console.log(response.status);
        //console.log(body);
        let responseBody = body.match("pendingBlocks");
        let pending = responseBody[1];
        console.log(pending);
    }
    catch(exception){
        console.log(exception);
    }
}

getCourseCode();

【问题讨论】:

  • body.match("pendingBlocks") 在正文的文本上执行正则表达式"pendingBlocks"。并将匹配的结果作为数组返回(在您的情况下,它将是 ["pendingBlocks"],因为您没有任何捕获组)。您将需要一些 html 解析器...
  • 从HTML中获取数据,最可靠的方法是使用healdess浏览器,比如github.com/puppeteer/puppeteer

标签: javascript node.js node-fetch


【解决方案1】:

我使用cheerio 来获取我的id 输出。我只是想分享一下,如果其他人正在寻找相同的 node.js。

const cheerio = require('cheerio');
const request = require('request');

request({
    method: 'GET',
    url: 'Website URL here'
}, (err, res, body) => {
    if (err) return console.error(err);
    $ = cheerio.load(body);
    var element = $('#pendingBlocks');
    var element2 = $('#confirmedBlocks');
    if (Number(element.text())+Number(element2.text()) === 0) {
    console.log('true')
}else{
  console.log('false')
}
});

【讨论】:

    猜你喜欢
    • 2022-06-12
    • 2019-03-31
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多