javascript - 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)
}
}
解决方案
在访问这些数组之前进行检查:price[0], sellername[0]
和imgsrc[0]
.
要检查开发,您可以使用
if(Array.isArray(price) && price.length > 0) {
price = price[0];
} else {
alert('Price array is empty')
}
推荐阅读
- macos - 在 zsh PS1(提示)环境变量中使用自定义颜色会导致空格问题
- kubernetes - 不同账户中的 Kops 实例组
- python - 在 WHILE 循环中将“行”添加到字典
- node.js - NodeJS Invalid_grant gaxios.js:85:23
- java - 如何打开whats app和gmail的选择器意图仅在kotlin中发送附件文档
- java - 我可以使用 JOOQ 对查询运行“解释分析”吗?
- java - jython 中的 Pythonnet
- android - Android Q、R 中的 WiFiManager API
- dbeaver - DBeaver:将服务器输出重定向到文件
- java - 与 java 具有相同属性的过滤器列表(首选 groovy)