2-я версия вопроса (первая ниже)
Я работаю в Интернете с разрешения, используя 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);
Первая версия вопроса: я пользуюсь веб-копированием с разрешения, используя Cheerio. У каждого сайта магазина есть свой путь прохождения информации. У меня есть массив объектов, содержащих информацию о сайте магазина. Я хотел бы отобразить этот массив в функцию, используя переменные, которые действительны внутри функции, но не внутри объекта. Если я кодирую его, как показано ниже, я получаю ошибку «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));