首页 > 解决方案 > TypeError: Cannot read property '0' of null, fetched URL

问题描述

I've some issues when I am trying to fetch the data and render in ReactFullpage Component.

The error says: TypeError: Cannot read property '0' of null

Since in the attached script he will get the data from the row here is an example for the var url = https://www.amazon.de/dp/B07YD776RP?ref=myi_title_dp

// script for scraping amazon data outgoing from an url

function import_amazon_data() {
  
//go to Google Sheet & get new income form column 4 
  var scraperSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("product_seller_data")
  
  var lrow =  scraperSheet.getLastRow();

  for(var i=2;i<=lrow;i++){
  
    var url = scraperSheet.getRange(i, 4).getValue() 

    var regExprice = /<span id="priceblock_ourprice.*<\/span>/gi 
    var regExsellername = /id=['"]sellerProfileTriggerId['"]>.*?<\/a>/gi
    var regEximgsrc = /data-old-hires=".*?"/gi

    var getContent = UrlFetchApp.fetch(url).getContentText().trim();

//match of HTML elements with fetched URL
    var price = getContent.match(regExprice)
    price = price[0]
    price = price.replace('<span id="priceblock_ourprice" class="a-size-medium a-color-price priceBlockBuyingPriceString">',"")
     .replace('</span>',"")
     
    scraperSheet.getRange(i, 6).setValue(price) 
    
    var sellername = getContent.match(regExsellername)
    sellername = sellername[0]
    sellername = sellername.replace("id='sellerProfileTriggerId'>","")
        .replace('id="sellerProfileTriggerId">',"")
        .replace('<\/a>',"")
     
    scraperSheet.getRange(i, 7).setValue(sellername)
     
    var imgsrc = getContent.match(regEximgsrc)
    imgsrc = imgsrc[0]
    imgsrc = imgsrc.replace('data-old-hires="',"")
        .replace('"',"")
     
     scraperSheet.getRange(i, 5).setValue(imgsrc)
     
    
}

 
}

标签: javascriptgoogle-apps-script

解决方案


在访问这些数组之前进行检查:price[0], sellername[0]imgsrc[0].

要检查开发,您可以使用

if(Array.isArray(price) && price.length > 0) {
   price = price[0];
} else {
    alert('Price array is empty')
}

推荐阅读