Script: Dynamically Updating Text Ads With Current Prices — Part 1

Technical Marketing
2 min readMay 2, 2020

One of Google Search Ads' best practices is writing the most relevant ad to the keyword. If the user searches for the product, sees the most up-to-date price, and clicks on the ad, there is a higher chance of conversion, and your marketing budget will be well spent.

It’s not always easy to get access to product prices API, and sometimes an alternative solution will be to scrape the product page and get the prices automatically. Luckily, it can be done using google ads scripts.

In this two-part article, I will scrape products into a spreadsheet database and then use this spreadsheet to update ads.

Scraping Product Pages

First, I’ll create a spreadsheet with links to the product pages. I’m using these links just for the sake of example:

Here’s the Google Ads Script. I’m using UrlFetchApp to scrape each URL from the table, then grab the price from the returned HTML with a custom function called html_splitter. I identify which HTML code came before and after the price and capture what was in the middle.

var SPREADSHEET_URL = “https://docs.google.com/spreadsheets/d/1UEME4mACJ";
var SHEET_NAME = “Final Urls”;
function main() {
var urls = get_urls();
var prices_dict = get_prices(urls);
update_spreadsheet(prices_dict);

}
function get_prices(urls){
var prices = {};
for (var i = 0; i < urls.length; i++) {
var html = UrlFetchApp.fetch(urls[i]).getContentText();
var price = html_splitter(html,’<span itemprop=”highPrice” content=”’,’”></span>’);
prices[urls[i]]=price;
}
return prices;
}
function get_urls(){
var ss = SPREADSHEET_URL;
var urls = [];
var sheet = SpreadsheetApp.openByUrl(ss).getSheetByName(SHEET_NAME);
var urls_array = sheet.getRange(2,1,sheet.getMaxRows() — 1,1).getValues();
for (var i = 0; i < urls_array.length; i++) {
if(urls_array[i] != “”) {
urls.push(urls_array[i]);
};
}
return urls;
}
function html_splitter(all,cut_to,cut_from){

var result = all.split(cut_to);
result = result[1].split(cut_from)[0];

return result;
}
function update_spreadsheet(prices_dict){

var ss = SPREADSHEET_URL;
var urls = [];
var sheet = SpreadsheetApp.openByUrl(ss).getSheetByName(SHEET_NAME);
sheet.clearContents();
sheet.appendRow([“Final Url”,”Prices”]);
for (var j in prices_dict) {
sheet.appendRow([j,prices_dict[j]]);
}
}

After running the script, the table is filled with the current prices.

--

--