如何解决使用库Cheerio.js,我想用一些字符串替换内容,而不是保留它
我已经用Cheerio.js库编写了一个内容抓取代码,它读取了网页的内容并为我获取了一些值,例如位置名称,街道地址和电话号码。
在某些地方,没有提供街道地址,因此它会跳过那个不太酷的地方。
这是我从中获取数据的网页示例。
如何检测街道地址是否不在此处,我的代码应该用其他内容替换空白内容?
完整代码位于此处。 https://github.com/jpca999/yellowpageScrapper/blob/master/indexWithAsyncArray.js
当前,在输出中,它只是跳过空的街道名称。
const getStreetAddress = async () => {
console.log(' calling getStreetAddress');
const html = await rp(baseURL + searchURL);
const businessMap = cheerio('div.street-address',html).map(async (i,e) => {
const streetAddress = e.children[0].parent.children[0].data;
console.log('Here it shold detect if the variable "streetAddress" has some value then leave it or else replace the value with something' );
return {
streetAddress,}
})
.get();
return Promise.all(businessMap);
};
这是输出。
解决方法
如果这是我的,但是不幸的是,我无法用您的整个代码库对此进行测试,我将对照默认值检查该值。我在JavaScript中使用的一些人喜欢而有些人不喜欢并且可以适应自己的口味的基本范例是
const actualValue = possibleValue || defaultValue;
所以您的情况可能是
const streetAddress = e.children[0].parent.children[0].data || 'No Street Address Provided';
这是因为null,undefined和空字符串都是假值,这样会导致分配默认值。
例如,返回对象后,您可以执行相同的操作
const businessMap = ... blah ... .get();
businessMap.streetAddress = businessMap.streetAddress || 'No Street Address Provided';
return Promise.all(businessMap);
,
该页面不会为我加载,但看起来应该像(假设streetAddress的CSS为.foo
)
const $ = cheerio.load(html)
const businessMap = $('div.street-address').get().map(div => {
return {
streetAddress: $(div).find('.foo').first().text() || "???"
}
})
还请注意,由于没有IO,cheerio不使用promise。
还要注意,在JS中,空字符串“”是错误的,这就是为什么这样的原因。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。