【发布时间】: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