function priceToInt(pPrice){ var res = parseInt(pPrice.replace(/\D/g, "")); return res; } function onOpen() { var ui = SpreadsheetApp.getUi(); ui.createMenu('Avito') .addItem('Update Prices', 'updatePrices') .addToUi(); } function updatePrices() { var sheet = SpreadsheetApp.getActiveSheet(); var ss = SpreadsheetApp.getActiveSpreadsheet(); var range = ss.getRangeByName('URL'); var firstRow = range.getRow(); var firstCol = range.getColumn(); var howManyRowsRead = 50; Logger.log('firstRow = ' + firstRow); Logger.log('firstCol = ' + firstCol); var data = sheet.getRange(firstRow, firstCol, howManyRowsRead, 1).getValues(); LLL: for (var i = 0; i < data.length; i++) { var url = data[i][0]; if (!url) break LLL; var prevPriceCell = sheet.getRange(firstRow+i, firstCol+2); var priceCell = sheet.getRange(firstRow+i, firstCol+1); prevPriceCell.setValue(priceCell.getValue()); priceCell.setValue('0'); var options = { headers : {'Cache-Control' : 'max-age=0', 'Referer': 'https://www.avito.ru/tolyatti/doma_dachi_kottedzhi/prodam?pmax=2700000&pmin=600000&geo=53.50804496509228%2C49.1193614935664%2C53.52551454627456%2C49.183133695104516%2C15%2Cf', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'}, muteHttpExceptions: true, }; var response = UrlFetchApp.fetch(url, options).getContentText(); var p1 = '<span itemprop="price">'; var l1 = response.indexOf(p1); var p2 = '</span>'; var l2 = response.indexOf(p2, l1 + p1.length); Logger.log('l1 = ' + l1); Logger.log('l2 = ' + l2); if (l1 != -1 && l2 != -1) { var price = response.substring(l1 + p1.length,l2); Logger.log('price = ' + price); priceInt = priceToInt(price); Logger.log('priceInt = ' + priceInt); priceCell.setValue(priceInt); } } }
Source: https://habr.com/ru/post/306894/
All Articles