gpt4 book ai didi

javascript - 从 request/cheerio 中提取数据

转载 作者:行者123 更新时间:2023-12-02 14:55:03 24 4
gpt4 key购买 nike

我目前正在开发一个项目,并且有一些关于 javascript/nodejs/request/cheerio 的问题。

request(address , function (error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
$('iframe').each(function(i, element){
var a = $(this).attr('src');
});

}});

所以我让上面的代码从一些网站上精确地抓取我想要的数据。我希望它稍后在某个模板中呈现它。然而,似乎 var a 只存在于上面的代码中,并且没有办法使其成为全局的(不介意)或以某种方式返回它。有任何想法吗?

最佳答案

使用 Promises 可以帮助我们轻松提取并稍后使用异步加载的数据。在下面的代码片段中,我将您的逻辑包装到一个函数中,该函数返回一个解析必要数据的 Promise:

function iframes(url) {
return new Promise((resolve, reject) => {
request(url , function (error, response, html) {
if (!error && response.statusCode == 200) {
const $ = cheerio.load(html);

// Extract list of each iframe's src attribute
const sources = $('iframe').map((i, element) => {
return element.attribs['src'];
}).get();

// Resolve iframe sources
resolve(sources);
return;
}

// You can pass more error information here
reject('error loading url for iframe sources');
});
});
}

我们可以像这样使用这个函数:

iframes('http://www.w3schools.com/html/html_iframe.asp')
.then(srcs => {
// Can access the sources
console.log(srcs);
})
.catch(err => console.log(err));

关于javascript - 从 request/cheerio 中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35872189/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com