我的一些承诺返回“未定义”,我看不出我做错了什么。 尝试添加超时但没有解决它,我仍在学习并努力发现我的错误。
看起来像是 scrapeSpecificOperatorStats 块上的问题,但是一些回报很好。
示例: 期待:
{
name: 'Kapkan',
imageUrl: 'https://staticctf.ubisoft.com/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7MofnDHeL1uwsenBVjxplQ/1e5af8fe9cf6f36516c7f6e5d56fcac0/r6-operators-list-kapkan.png',
linkUrl: 'https://www.ubisoft.com/en-us/game/rainbow-six/siege/game-info/operators/kapkan',
operatorStats: { specialty: 'ANTI-ENTRY, TRAPPER' }
}
实际:
{
name: 'Kapkan',
imageUrl: 'https://staticctf.ubisoft.com/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7MofnDHeL1uwsenBVjxplQ/1e5af8fe9cf6f36516c7f6e5d56fcac0/r6-operators-list-kapkan.png',
linkUrl: 'https://www.ubisoft.com/en-us/game/rainbow-six/siege/game-info/operators/kapkan',
operatorStats: undefined
}
问题仅出现在 operatorStats 上并且仅针对某些元素
我的代码:
const axios = require("axios");
const cheerio = require("cheerio");
// Define the URL of the webpage
const url = "https://www.ubisoft.com/en-us/game/rainbow-six/siege/game-info/operators";
// Define a function to scrape the operator stats from the link URL
const scrapeSpecificOperatorStats = async (link) => {
try {
// Make a HTTP request to the webpage
const response = await axios.get(link);
// Load the HTML content into Cheerio
const $ = cheerio.load(response.data);
// Find and Extract the operator specialty
const specialty = $("span.operator__header__roles").text();
// Return the results
return { specialty };
} catch (error) {
console.error(error);
}
};
// Define a function to scrape the operator stats
const scrapeOperatorStats = async (url) => {
try {
// Make a HTTP request to the webpage
const response = await axios.get(url);
// Load the HTML content into Cheerio
const $ = cheerio.load(response.data);
// Find the element that contains the operator stats
const statsElement = $(".oplist__card");
// Create an array of promises for each operator stat element
const statsPromises = statsElement.map(async (index, element) => {
// Extract the operator name, specialty, and description
const name = $(element).find("span").text();
// Extract the image URL and link URL
const imageUrl = $(element).find("img").attr("src");
const linkUrl = "https://www.ubisoft.com" + $(element).attr("href");
// Get the operator stats
const operatorStats = await scrapeSpecificOperatorStats(linkUrl);
// Return the result
return {
name,
imageUrl,
linkUrl,
operatorStats,
};
});
// Wait for all promises to resolve and return the results
return Promise.all(statsPromises);
} catch (error) {
console.error(error);
}
};
// Call the function and log the results
scrapeOperatorStats(url)
.then((results) => console.log(results))
.catch((error) => console.error(error));
问题是,当发生错误时,
scrapeSpecificOperatorStats
返回undefined
,因为你有一个try
/catch
,而catch
只是注销错误。这意味着执行会从函数末尾开始,隐式返回 undefined
。
要修复此问题,要么允许
scrapeSpecificOperatorStats
中的错误传播,而不是将其转换为 undefined
(通过删除 try
/catch
)并在更高级别处理它们(例如在 scrapeOperatorStats
中),或者处理发生错误时 scrapeSpecificOperatorStats
返回 undefined
的事实。最好的选择通常是前者;过早处理错误是一种常见的反模式。