Web Scraping Amazon “查看更多购买选项” Node Cheerio Puppeteer

问题描述

我正在尝试通过网络抓取亚马逊的 GPU 价格(多么原始!)。我是一名小学老师,正在尝试一个有趣的初学者节点项目来获取亚马逊上的价格。

我在抓取时发现了三个选项...可用 添加到购物车、查看其他购买选项,目前不可用。

我已经能够通过检查长度来查看“添加到购物车”按钮是否存在,并且可以抓取价格以查看我是否愿意支付,然后提醒我。但是,在检查其他购买选项时,我可以进入侧窗格,但我无法抓取其他购买选项的价格,因为cheerio 看不到特定 ID。每个“购买选项”div 都有一个 ID="#aod-offer",但即使查看它是否存在,它也会返回 0,即使我在检查器中清楚地看到它。我一直在至少有 1 个购买选项的页面上练习。不知道为什么它没有抓取任何数据。

我一直在练习这张卡: https://www.amazon.com/Gaming-GeForce-Graphics-DisplayPort-Bearings/dp/B08TFLDLTM/ref=sr_1_17?crid=1FL7W42YBL5XB&dchild=1&keywords=geforce+rtx+3080+graphics+card&qid=1617721759&s=electronics&sprefix=GeForce+rtx+3080+graphics+card%2Celectronics%2C173&sr=1-17

//Scrapes amazon pages
async function CheckAvailability(page){

//for(var i = 0; i < items.length; i++){}
await page.goto(items[1].url);
const html = await page.content();
const $ = cheerio.load(html);
    
//If add to cart button is present
if($("#add-to-cart-button").length > 0){
    
    //Check price of item
    const priceStr = $("#price_inside_buyBox").text().replace("$","");
    const price = Number(priceStr);
    console.log(priceStr);
    console.log(price);

    //Check price against what you are willing to spend
     if(checkPrice(price)){
        console.log("You are willing to buy this item");
     }else{
        console.log("The price is too rich for your blood!");
     }

// Check if there are other sellers
}else if ($("#unqualifiedBuyBox").length > 0){
    console.log("There might be others");
    await page.$eval("a[title ='See All Buying Options']",elem => elem.click());
    await page.waitFor(2000);
    
    const offers = [];
    const offerListings = $("#aod-offer").each((i,e) => {
        offers[i] = $(e).html();
    });
    console.log(offers);
       

// Currently unavailable is displayed
}else if ($("#outOfStock").length > 0){
    console.log("There are none available,moving on...");
}
}

//Checks a price against what I'm willing to spend.  Lowered the number for testing.  I kNow I cannot 
get a gpu for $200
function checkPrice(price){
if (price < 200){
    return true;
}else{
    return false;
}
}

解决方法

我知道我的代码可能非常基础,但是我将 const $ 更改为 Let $ 并在 else if 部分使用新的 HTML 数据重新加载了cheerio,并且它起作用了。我认为因为我在同一页面上,所以我的cheerio 不必更新,但显然更新了。