缩略图"/>
使用 Cheerio 和 Nodejs 抓取 ebay 图像缩略图
我可以使用 Nodejs、Axios 和 Cheerio 从 ebay 搜索中获取标题、价格、日期等,但是我无法将 img 缩略图 url 放入我的 items.json 文件中。
这是我获取易趣搜索和选择数据的代码:
const fs = require('fs');
const axios = require('axios');
const cheerio = require('cheerio');
async function scrapeEBayItems(url) {
try {
const response = await axios.get(url);
const $ = cheerio.load(response.data);
const items = [];
$('li.s-item').each((index, element) => {
const title = $(element).find('div.s-item__title').text().trim();
const image = $(element).find('a.s-item__image-wrapper.image-treatment').attr('img');
const price = $(element).find('span.s-item__price').text().trim();
const date = $(element).find('span.s-item__listingDate').text().trim();
const shipping = $(element).find('span.s-item__shipping.s-item__logisticsCost').text().trim();
const itemUrl = $(element).find('a.s-item__link').attr('href');
items.push({
title,
image,
price,
date,
shipping,
itemUrl
});
});
const data = JSON.stringify(items, null, 2);
fs.writeFileSync('items.json', data);
console.log(`Scraped ${items.length} items from ${url}`);
} catch (error) {
console.error(error);
}
}
scrapeEBayItems('.html?_nkw=stack+overflow&_saact=1&LH_AvailTo=1&_sop=10&LH_BIN=1');
produced items.json 项目如下所示:
{
"title": "OVERFLOW: LIVING ABOVE LIFE'S LIMITS By Hagin Kenneth Jr **Mint Condition**",
"price": "THB618.28",
"date": "Apr-4 16:43",
"shipping": "+THB964.11 shipping",
"itemUrl": ";hash=item2b451b2358%3Ag%3AgcwAAOSw-TlkLLYg&amdata=enc%3AAQAIAAAAwBNfcRQy1hqZOILlpIg9qzmF2xeYVuewSycduJC7Tobp51lv5NrYtVauVVrI83ASg%2BfGc2lppd3JMWvoRP21tXgKoCLdwYCkiewNfo%2F6LVl%2F0X6HH2jZVl09c6UkY5dRcZZxw0akbrWpXPFOOZ33RlFYZdn%2FDCiIZFP6MqSzLN7an4LoD%2BkgAoFaL0B4vfcQCaXZuOMuDA64ki56Zho%2FuB%2Fb4T%2BZi6Vau%2FOqDdze04%2FHfArHuVdyrzDhyIXu0PN19w%3D%3D%7Ctkp%3ABk9SR-Lw0Nf1YQ&LH_BIN=1"
},
这是我试图从中提取图像 url 的片段:
<div class="s-item__image-wrapper image-treatment"><img src=".webp" loading="eager" fetchpriority="high" onload="SITE_SPEED.ATF_TIMER.measure(this); if (performance && performance.mark) { performance.mark("first-meaningful-paint"); };if(this.width === 80 && this.height === 80) {window.SRP.metrics.incrementCounter('imageEmptyError');}" onerror="window.SRP.metrics.incrementCounter('imageLoadError');" alt="OVERFLOW: LIVING ABOVE LIFE'S LIMITS By Hagin Kenneth Jr **Mint Condition**" data-atftimer="1682242917643"></div>
我想要这条线:
"image": ".webp",
作为 item.json 文件的一部分。
我尝试了大约三十种不同的
const image = $(element).find('a.s-item__image-wrapper.image-treatment').attr('img');
但是好像抓不到img地址
回答如下:您正在尝试选择具有
img
类的某些 a
标签的 ...
属性,但需要在具有 src
类的 img
中选择 div
的 ...
属性,因此您应该变化:
const image = $(element).find('a.s-item__image-wrapper.image-treatment').attr('img');
到
const image = $(element).find('div.s-item__image-wrapper.image-treatment > img').attr('src');
更多推荐
使用 Cheerio 和 Nodejs 抓取 ebay 图像缩略图
发布评论