问题的第二版(下文第一稿)
我正在使用Cheerio的许可进行网络抓取。每个商店网站对其信息都有不同的遍历路径。我有一个包含存储网站信息的对象数组。在下面响应的帮助下,我为productTitle键使用了一个箭头函数,但它返回为空白。
const sellerArray = [
{
sellerUrl: 'https://www.thebeststoreever.com',
sellerName: 'The Best Store Ever',
productTitleFn: ($) => $(this).find('h3').text().trim()
}
];
axios(sellerArray[0].sellerUrl)
.then(response => {
const html = response.data;
const $ = cheerio.load(html);
const productTable = $('.plusplus');
productTable.each(function () {
const id=uuid();
const seller = sellerArray[0].sellerName;
const productTitle = $(this).find('h3').text().trim();
console.log(productTitle); //returns "The Greatest Product Ever"
const productTitleFn = sellerArray[0].productTitleFn($);
console.log(productTitleFn); //returns blank
});
})
.catch(console.error);第一个版本的问题:我是网络刮擦与许可使用啦啦队。每个商店网站对其信息都有不同的遍历路径。我有一个包含存储网站信息的对象数组。我想使用函数内部有效的变量将这个数组映射到一个函数,而不是在对象内。如果我像下面这样编码,我会得到错误'html是没有定义‘。如果我把引号放在'productTitle‘值周围,当然它只是传递一个字符串。我该怎么处理这个?
const sellerArray = [
{
sellerUrl: 'https://beststoreever.com'
sellerName: 'Best Store Ever',
producTitleTraversalPath: html(this).find('h3').text().trim(),
},
{
sellerUrl: 'https://2ndbeststoreever.com',
sellerName: '2nd Best Store Ever',
producTitleTraversalPath: html(this).find('.myProduct').children[0].text().trim(),
}
]
function parseStoreInfo(seller, data) {
const html = cheerio.load(data);
const products = html('.sellerProductsTableName');
products.map(item => {
const id=uuid();
const sellerName = seller.sellerName;
const productTitle = seller.productTitleTraversalPath;
//push to myProductArray for future use
});
}
sellerArray.map(seller => axios(seller.sellerUrl)
.then(response => {
parseStoreInfo(seller, response.data);
})
.catch(console.error));发布于 2020-03-06 18:36:24
原来这是个“这个”问题:
明白了!我将对象内的函数更改为(在这一行代码中不要使用' this‘):
productTitleFn: ($, item) => $(item).find('h3').text().trim() 我将函数调用更改为:
const productTitleFn = sellerArray[0].productTitleFn($, this);发布于 2020-03-06 15:54:21
尝试将“提取标题”部分定义为数组中的function,如下所示:
productTitleTraversalFn: function(obj) { return obj.find('h3').text().trim(); }或者使用箭头函数符号:
productTitleTraversalFn: obj => obj.find('h3').text().trim();然后,当对象加载时,您可以按照
const productTitle = productTitleTraversalFn($(this));https://stackoverflow.com/questions/60567268
复制相似问题