Automação Google Ads: Palavras-chave

Spread the love

Nessa série especial, reunimos alguns scripts úteis para você automatizar e aumentar o retorno de suas campanhas no Google Ads. Confira abaixo como automatizar o Google Ads para “Trabalhar com Palavras-chave”.

 

1. Palavras-chave “exatas” – Por Brainlabs. O script faz com que suas palavras-chave sejam exatamente o que estão sendo digitadas, eliminando as variações aproximadas, como erros de digitação, plural, etc.

/**
*
* Adds as campaign or AdGroup negatives search queries which have triggered exact keywords
* Version: 1.1
* Updated: 2015-10-26
* Authors: Visar Shabi & Daniel Gilbert
* brainlabsdigital.com
*
**/
function main() {

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Options

//Choose whether to add your negative exact keywords at campaign or AdGroup level.
//Set variable as “true” to add or as “false” to not add.
var AddAdGroupNegative = true; // true or false
var AddCampaignNegative = true; // true of false

//Parameters for filtering by campaign name and AdGroup name. The filtering is case insensitive.
//Leave blank, i.e. “”, if you want this script to run over all campaigns and AdGroups.
var campaignNameContains = “”;
var adGroupNameContains = “”;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//

var campaigns = {};
var adGroups = {};

var exactKeywords = [];

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Pull a list of all exact match keywords in the account

var report = AdWordsApp.report(
“SELECT AdGroupId, Id ” +
“FROM KEYWORDS_PERFORMANCE_REPORT ” +
“WHERE Impressions > 0 AND KeywordMatchType = EXACT ” +
“DURING LAST_7_DAYS”);

var rows = report.rows();
while (rows.hasNext()) {
var row = rows.next();
var keywordId = row[‘Id’];
var adGroupId = row[‘AdGroupId’];
exactKeywords.push(adGroupId + “#” + keywordId);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Pull a list of all exact (close variant) search queries

var report = AdWordsApp.report(
“SELECT Query, AdGroupId, CampaignId, KeywordId, KeywordTextMatchingQuery, Impressions, QueryMatchTypeWithVariant ” +
“FROM SEARCH_QUERY_PERFORMANCE_REPORT ” +
“WHERE CampaignName CONTAINS_IGNORE_CASE ‘” + campaignNameContains + “‘ ” +
“AND AdGroupName CONTAINS_IGNORE_CASE ‘” + adGroupNameContains + “‘ ” +
“DURING LAST_7_DAYS”);

var rows = report.rows();
while (rows.hasNext()) {
var row = rows.next();
var adGroupId = parseInt(row[‘AdGroupId’]);
var campaignId = parseInt(row[‘CampaignId’]);
var keywordId = parseInt(row[‘KeywordId’]);
var searchQuery = row[‘Query’].toLowerCase();
var keyword = row[‘KeywordTextMatchingQuery’].toLowerCase();
var matchType = row[‘QueryMatchTypeWithVariant’].toLowerCase();
if(keyword !== searchQuery && matchType.indexOf(“exact (close variant)”) !== -1){

if(!campaigns.hasOwnProperty(campaignId)){
campaigns[campaignId] = [[], []];
}

campaigns[campaignId][0].push(searchQuery);
campaigns[campaignId][1].push(adGroupId + “#” + keywordId);

if(!adGroups.hasOwnProperty(adGroupId)){
adGroups[adGroupId] = [[], []];
}

adGroups[adGroupId][0].push(searchQuery);
adGroups[adGroupId][1].push(adGroupId + “#” + keywordId);
}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Parse data correctly

var adGroupIds = [];
var campaignIds = [];
var adGroupNegatives = [];
var campaignNegatives = [];

for(var x in campaigns){
campaignIds.push(parseInt(x));
campaignNegatives.push([]);
for(var y = 0; y < campaigns[x][0].length; y++){
var keywordId = campaigns[x][1][y];
var keywordText = campaigns[x][0][y];
if(exactKeywords.indexOf(keywordId) !== -1){
campaignNegatives[campaignIds.indexOf(parseInt(x))].push(keywordText);
}
}
}

for(var x in adGroups){
adGroupIds.push(parseInt(x));
adGroupNegatives.push([]);
for(var y = 0; y < adGroups[x][0].length; y++){
var keywordId = adGroups[x][1][y];
var keywordText = adGroups[x][0][y];
if(exactKeywords.indexOf(keywordId) !== -1){
adGroupNegatives[adGroupIds.indexOf(parseInt(x))].push(keywordText);
}
}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Create the new negative exact keywords

var campaignResults = {};
var adGroupResults = {};

if(AddCampaignNegative){
var campaignIterator = AdWordsApp.campaigns()
.withIds(campaignIds)
.get();
while(campaignIterator.hasNext()){
var campaign = campaignIterator.next();
var campaignId = campaign.getId();
var campaignName = campaign.getName();
var campaignIndex = campaignIds.indexOf(campaignId);
for(var i = 0; i < campaignNegatives[campaignIndex].length; i++){
campaign.createNegativeKeyword(“[” + campaignNegatives[campaignIndex][i] + “]”)
if(!campaignResults.hasOwnProperty(campaignName)){
campaignResults[campaignName] = [];
}
campaignResults[campaignName].push(campaignNegatives[campaignIndex][i]);
}
}
}

if(AddAdGroupNegative){
var adGroupIterator = AdWordsApp.adGroups()
.withIds(adGroupIds)
.get();
while(adGroupIterator.hasNext()){
var adGroup = adGroupIterator.next();
var adGroupId = adGroup.getId();
var adGroupName = adGroup.getName();
var adGroupIndex = adGroupIds.indexOf(adGroupId);
for(var i = 0; i < adGroupNegatives[adGroupIndex].length; i++){
adGroup.createNegativeKeyword(“[” + adGroupNegatives[adGroupIndex][i] + “]”);
if(!adGroupResults.hasOwnProperty(adGroupName)){
adGroupResults[adGroupName] = [];
}
adGroupResults[adGroupName].push(adGroupNegatives[adGroupIndex][i]);
}
}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Format the results

var resultsString = “The following negative keywords have been added to the following campaigns:”;

for(var x in campaignResults){
resultsString += “\n\n” + x + “:\n” + campaignResults[x].join(“\n”);
}

resultsString += “\n\n\n\nThe following negative keywords have been added to the following AdGroups:”;

for(var x in adGroupResults){
resultsString += “\n\n” + x + “:\n” + adGroupResults[x].join(“\n”);
}

Logger.log(resultsString);

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//

}

 

2. Oportunidades de Termos de Pesquisa – Por Daniel Gilbert. Utilize esse scripts para gerar insights dos termos que são buscados e que geraram boas conversões ou apenas custos. Ele quebra as palavras nos termos de pesquisa e organiza por custo e conversão, assim você poderá ter uma ideia de que tipo palavras estão gerando conversão ou apenas custos. Excelente script para buscar termos de cauda longa e analisar seu desempenho.

/**
*
* Search Query Mining Tool
*
* This script calculates the contribution of each word found in the search query report
* and outputs a report into a Google Doc spreadsheet.
*
* Version: 1.0
* Google Apps Script maintained on brainlabsdigital.com
*
**/

function main() {

//////////////////////////////////////////////////////////////////////////////
// Options

var startDate = “2015-04-01”;
var endDate = “2015-04-30”;
// The start and end date of the date range for your search query data
// Format is yyyy-mm-dd

var currencySymbol = “£”;
// The currency symbol used for formatting. For example “£”, “$” or “€”.

var campaignNameContains = “”;
// Use this if you only want to look at some campaigns
// such as campaigns with names containing ‘Brand’ or ‘Shopping’.
// Leave as “” if not wanted.

var spreadsheetUrl = “//docs.google.com/YOUR-SPREADSHEET-URL-HERE”;
// The URL of the Google Doc the results will be put into.

//////////////////////////////////////////////////////////////////////////////

// Thresholds

var impressionThreshold = 10;
var clickThreshold = 0;
var costThreshold = 0;
var conversionThreshold = 0;
// Words will be ignored if their statistics are lower than any of these thresholds

//////////////////////////////////////////////////////////////////////////////
// Find the negative keywords

var negativesByGroup = [];
var negativesByCampaign = [];
var sharedSetData = [];
var sharedSetNames = [];
var sharedSetCampaigns = [];
var dateRange = startDate.replace(/-/g, “”) + “,” + endDate.replace(/-/g, “”);
var activeCampaignIds = [];

// Gather ad group level negative keywords

var keywordReport = AdWordsApp.report(
“SELECT CampaignId, AdGroupId, KeywordText, KeywordMatchType ” +
“FROM KEYWORDS_PERFORMANCE_REPORT ” +
“WHERE CampaignStatus = ENABLED AND AdGroupStatus = ENABLED AND Status = ENABLED AND IsNegative = TRUE ” +
“AND CampaignName CONTAINS_IGNORE_CASE ‘” + campaignNameContains + “‘ ” +
“DURING ” + dateRange);

var keywordRows = keywordReport.rows();
while (keywordRows.hasNext()) {
var keywordRow = keywordRows.next();

if (negativesByGroup[keywordRow[“AdGroupId”]] == undefined) {
negativesByGroup[keywordRow[“AdGroupId”]] =
[[keywordRow[“KeywordText”].toLowerCase(),keywordRow[“KeywordMatchType”].toLowerCase()]];
} else {

negativesByGroup[keywordRow[“AdGroupId”]].push([keywordRow[“KeywordText”].toLowerCase(),keywordRow[“KeywordMatchType”].toLowerCase()]);
}

if (activeCampaignIds.indexOf(keywordRow[“CampaignId”]) < 0) {
activeCampaignIds.push(keywordRow[“CampaignId”]);
}
}//end while

// Gather campaign level negative keywords

var campaignNegReport = AdWordsApp.report(
“SELECT CampaignId, KeywordText, KeywordMatchType ” +
“FROM CAMPAIGN_NEGATIVE_KEYWORDS_PERFORMANCE_REPORT ” +
“WHERE IsNegative = TRUE ” +
“AND CampaignId IN [” + activeCampaignIds.join(“,”) + “]”
);
var campaignNegativeRows = campaignNegReport.rows();
while (campaignNegativeRows.hasNext()) {
var campaignNegativeRow = campaignNegativeRows.next();

if (negativesByCampaign[campaignNegativeRow[“CampaignId”]] == undefined) {
negativesByCampaign[campaignNegativeRow[“CampaignId”]] = [[campaignNegativeRow[“KeywordText”].toLowerCase(),campaignNegativeRow[“KeywordMatchType”].toLowerCase()]];
} else {

negativesByCampaign[campaignNegativeRow[“CampaignId”]].push([campaignNegativeRow[“KeywordText”].toLowerCase(),campaignNegativeRow[“KeywordMatchType”].toLowerCase()]);
}
}//end while

// Find which campaigns use shared negative keyword sets

var campaignSharedReport = AdWordsApp.report(
“SELECT CampaignName, CampaignId, SharedSetName, SharedSetType, Status ” +
“FROM CAMPAIGN_SHARED_SET_REPORT ” +
“WHERE SharedSetType = NEGATIVE_KEYWORDS ” +
“AND CampaignName CONTAINS_IGNORE_CASE ‘” + campaignNameContains + “‘”);
var campaignSharedRows = campaignSharedReport.rows();
while (campaignSharedRows.hasNext()) {
var campaignSharedRow = campaignSharedRows.next();

if (sharedSetCampaigns[campaignSharedRow[“SharedSetName”]] == undefined) {
sharedSetCampaigns[campaignSharedRow[“SharedSetName”]] = [campaignSharedRow[“CampaignId”]];
} else {

sharedSetCampaigns[campaignSharedRow[“SharedSetName”]].push(campaignSharedRow[“CampaignId”]);
}
}//end while

// Map the shared sets’ IDs (used in the criteria report below)
// to their names (used in the campaign report above)

var sharedSetReport = AdWordsApp.report(
“SELECT Name, SharedSetId, MemberCount, ReferenceCount, Type ” +
“FROM SHARED_SET_REPORT ” +
“WHERE ReferenceCount > 0 AND Type = NEGATIVE_KEYWORDS “);
var sharedSetRows = sharedSetReport.rows();
while (sharedSetRows.hasNext()) {
var sharedSetRow = sharedSetRows.next();
sharedSetNames[sharedSetRow[“SharedSetId”]] = sharedSetRow[“Name”];
}//end while

// Collect the negative keyword text from the sets,
// and record it as a campaign level negative in the campaigns that use the set

var sharedSetReport = AdWordsApp.report(
“SELECT SharedSetId, KeywordMatchType, KeywordText ” +
“FROM SHARED_SET_CRITERIA_REPORT “);
var sharedSetRows = sharedSetReport.rows();
while (sharedSetRows.hasNext()) {
var sharedSetRow = sharedSetRows.next();
var setName = sharedSetNames[sharedSetRow[“SharedSetId”]];
if (sharedSetCampaigns[setName] !== undefined) {
for (var i=0; i<sharedSetCampaigns[setName].length; i++) {
var campaignId = sharedSetCampaigns[setName][i];
if (negativesByCampaign[campaignId] == undefined) {
negativesByCampaign[campaignId] =
[[sharedSetRow[“KeywordText”].toLowerCase(),sharedSetRow[“KeywordMatchType”].toLowerCase()]];
} else {

negativesByCampaign[campaignId].push([sharedSetRow[“KeywordText”].toLowerCase(),sharedSetRow[“KeywordMatchType”].toLowerCase()]);
}
}
}
}//end while

Logger.log(“Finished negative keyword lists.”);

//////////////////////////////////////////////////////////////////////////////
// Defines the statistics to download or calculate, and their formatting

var statColumns = [“Clicks”, “Impressions”, “Cost”, “ConvertedClicks”, “ConversionValue”];
var calculatedStats = [[“CTR”,”Clicks”,”Impressions”],
[“CPC”,”Cost”,”Clicks”],
[“Conv. Rate”,”ConvertedClicks”,”Clicks”],
[“Cost / conv.”,”Cost”,”ConvertedClicks”],
[“Conv. value/cost”,”ConversionValue”,”Cost”]]
var currencyFormat = currencySymbol + “#,##0.00”;
var formatting = [“#,##0”, “#,##0”, currencyFormat, “#,##0″, currencyFormat,”0.00%”,currencyFormat,”0.00%”,currencyFormat,”0.00%”];

//////////////////////////////////////////////////////////////////////////////
// Go through the search query report, remove searches already excluded by negatives
// record the performance of each word in each remaining query

var queryReport = AdWordsApp.report(
“SELECT CampaignName, CampaignId, AdGroupId, AdGroupName, Query, ” + statColumns.join(“, “) + ” ” +
“FROM SEARCH_QUERY_PERFORMANCE_REPORT ” +
“WHERE CampaignStatus = ENABLED AND AdGroupStatus = ENABLED ” +
“AND CampaignName CONTAINS_IGNORE_CASE ‘” + campaignNameContains + “‘ ” +
“DURING ” + dateRange);

var campaignSearchWords = [];
var totalSearchWords = [];
var totalSearchWordsKeys = [];
var numberOfWords = [];

var queryRows = queryReport.rows();
while (queryRows.hasNext()) {
var queryRow = queryRows.next();
var searchIsExcluded = false;

// Checks if the query is excluded by an ad group level negative

if (negativesByGroup[queryRow[“AdGroupId”]] !== undefined) {
for (var i=0; i<negativesByGroup[queryRow[“AdGroupId”]].length; i++) {
if ( (negativesByGroup[queryRow[“AdGroupId”]][i][1] == “exact” &&
queryRow[“Query”] == negativesByGroup[queryRow[“AdGroupId”]][i][0]) ||
(negativesByGroup[queryRow[“AdGroupId”]][i][1] != “exact” &&
(” “+queryRow[“Query”]+” “).indexOf(” “+negativesByGroup[queryRow[“AdGroupId”]][i][0]+” “) > -1 )){
searchIsExcluded = true;
break;
}
}
}

// Checks if the query is excluded by a campaign level negative

if (!searchIsExcluded && negativesByCampaign[queryRow[“CampaignId”]] !== undefined) {
for (var i=0; i<negativesByCampaign[queryRow[“CampaignId”]].length; i++) {
if ( (negativesByCampaign[queryRow[“CampaignId”]][i][1] == “exact” &&
queryRow[“Query”] == negativesByCampaign[queryRow[“CampaignId”]][i][0]) ||
(negativesByCampaign[queryRow[“CampaignId”]][i][1]!= “exact” &&
(” “+queryRow[“Query”]+” “).indexOf(” “+negativesByCampaign[queryRow[“CampaignId”]][i][0]+” “) > -1 )){
searchIsExcluded = true;
break;
}
}
}

if (searchIsExcluded) {continue;}
// if the search is already excluded by the current negatives,
// we ignore it and go on to the next query

var currentWords = queryRow[“Query”].split(” “);
var doneWords = [];

if (campaignSearchWords[queryRow[“CampaignName”]] == undefined) {
campaignSearchWords[queryRow[“CampaignName”]] = [];
}

var wordLength = currentWords.length;
if (wordLength > 6) {
wordLength = “7+”;
}
if (numberOfWords[wordLength] == undefined) {
numberOfWords[wordLength] = [];
}
for (var i=0; i<statColumns.length; i++) {
if (numberOfWords[wordLength][statColumns[i]] > 0) {
numberOfWords[wordLength][statColumns[i]] += parseFloat(queryRow[statColumns[i]].replace(/,/g, “”));
} else {
numberOfWords[wordLength][statColumns[i]] = parseFloat(queryRow[statColumns[i]].replace(/,/g, “”));
}
}

// Splits the query into words and records the stats for each

for (var w=0;w<currentWords.length;w++) {
if (doneWords.indexOf(currentWords[w]) < 0) { //if this word hasn’t been in the query yet

if (campaignSearchWords[queryRow[“CampaignName”]][currentWords[w]] == undefined) {
campaignSearchWords[queryRow[“CampaignName”]][currentWords[w]] = [];
}
if (totalSearchWords[currentWords[w]] == undefined) {
totalSearchWords[currentWords[w]] = [];
totalSearchWordsKeys.push(currentWords[w]);
}

for (var i=0; i<statColumns.length; i++) {
var stat = parseFloat(queryRow[statColumns[i]].replace(/,/g, “”));
if (campaignSearchWords[queryRow[“CampaignName”]][currentWords[w]][statColumns[i]] > 0) {
campaignSearchWords[queryRow[“CampaignName”]][currentWords[w]][statColumns[i]] += stat;
} else {
campaignSearchWords[queryRow[“CampaignName”]][currentWords[w]][statColumns[i]] = stat;
}
if (totalSearchWords[currentWords[w]][statColumns[i]] > 0) {
totalSearchWords[currentWords[w]][statColumns[i]] += stat;
} else {
totalSearchWords[currentWords[w]][statColumns[i]] = stat;
}
}

doneWords.push(currentWords[w]);
}//end if
}//end for
}//end while

Logger.log(“Finished analysing queries.”);

//////////////////////////////////////////////////////////////////////////////
// Output the data into the spreadsheet

var campaignSearchWordsOutput = [];
var campaignSearchWordsFormat = [];
var totalSearchWordsOutput = [];
var totalSearchWordsFormat = [];
var wordLengthOutput = [];
var wordLengthFormat = [];

// Add headers

var calcStatNames = [];
for (var s=0; s<calculatedStats.length; s++) {
calcStatNames.push(calculatedStats[s][0]);
}
var statNames = statColumns.concat(calcStatNames);
campaignSearchWordsOutput.push([“Campaign”,”Word”].concat(statNames));
totalSearchWordsOutput.push([“Word”].concat(statNames));
wordLengthOutput.push([“Word count”].concat(statNames));

// Output the campaign level stats

for (var campaign in campaignSearchWords) {
for (var word in campaignSearchWords[campaign]) {

if (campaignSearchWords[campaign][word][“Impressions”] < impressionThreshold) {continue;}
if (campaignSearchWords[campaign][word][“Clicks”] < clickThreshold) {continue;}
if (campaignSearchWords[campaign][word][“Cost”] < costThreshold) {continue;}
if (campaignSearchWords[campaign][word][“ConvertedClicks”] < conversionThreshold) {continue;}

// skips words under the thresholds

var printline = [campaign, word];

for (var s=0; s<statColumns.length; s++) {
printline.push(campaignSearchWords[campaign][word][statColumns[s]]);
}

for (var s=0; s<calculatedStats.length; s++) {
var multiplier = calculatedStats[s][1];
var divisor = calculatedStats[s][2];
if (campaignSearchWords[campaign][word][divisor] > 0) {
printline.push(campaignSearchWords[campaign][word][multiplier] / campaignSearchWords[campaign][word][divisor]);
} else {
printline.push(“-“);
}
}

campaignSearchWordsOutput.push(printline);
campaignSearchWordsFormat.push(formatting);
}
} // end for

totalSearchWordsKeys.sort(function(a,b) {return totalSearchWords[b][“Cost”] – totalSearchWords[a][“Cost”];});

for (var i = 0; i<totalSearchWordsKeys.length; i++) {
var word = totalSearchWordsKeys[i];

if (totalSearchWords[word][“Impressions”] < impressionThreshold) {continue;}
if (totalSearchWords[word][“Clicks”] < clickThreshold) {continue;}
if (totalSearchWords[word][“Cost”] < costThreshold) {continue;}
if (totalSearchWords[word][“ConvertedClicks”] < conversionThreshold) {continue;}

// skips words under the thresholds

var printline = [word];

for (var s=0; s<statColumns.length; s++) {
printline.push(totalSearchWords[word][statColumns[s]]);
}

for (var s=0; s<calculatedStats.length; s++) {
var multiplier = calculatedStats[s][1];
var divisor = calculatedStats[s][2];
if (totalSearchWords[word][divisor] > 0) {
printline.push(totalSearchWords[word][multiplier] / totalSearchWords[word][divisor]);
} else {
printline.push(“-“);
}
}

totalSearchWordsOutput.push(printline);
totalSearchWordsFormat.push(formatting);
} // end for

for (var i = 1; i<8; i++) {
if (i < 7) {
var wordLength = i;
} else {
var wordLength = “7+”;
}

var printline = [wordLength];

if (numberOfWords[wordLength] == undefined) {
printline.push([0,0,0,0,”-“,”-“,”-“,”-“]);
} else {
for (var s=0; s<statColumns.length; s++) {
printline.push(numberOfWords[wordLength][statColumns[s]]);
}

for (var s=0; s<calculatedStats.length; s++) {
var multiplier = calculatedStats[s][1];
var divisor = calculatedStats[s][2];
if (numberOfWords[wordLength][divisor] > 0) {
printline.push(numberOfWords[wordLength][multiplier] / numberOfWords[wordLength][divisor]);
} else {
printline.push(“-“);
}
}
}

wordLengthOutput.push(printline);
wordLengthFormat.push(formatting);
} // end for

// Finds available names for the new sheets

var campaignWordName = “Campaign Word Analysis”;
var totalWordName = “Total Word Analysis”;
var wordCountName = “Word Count Analysis”;
var campaignWordSheet = SpreadsheetApp.openByUrl(spreadsheetUrl).getSheetByName(campaignWordName);
var totalWordSheet = SpreadsheetApp.openByUrl(spreadsheetUrl).getSheetByName(totalWordName);
var wordCountSheet = SpreadsheetApp.openByUrl(spreadsheetUrl).getSheetByName(wordCountName);
var i = 1;
while (campaignWordSheet != null || wordCountSheet != null || totalWordSheet != null) {
campaignWordName = “Campaign Word Analysis ” + i;
totalWordName = “Total Word Analysis ” + i;
wordCountName = “Word Count Analysis ” + i;
campaignWordSheet = SpreadsheetApp.openByUrl(spreadsheetUrl).getSheetByName(campaignWordName);
totalWordSheet = SpreadsheetApp.openByUrl(spreadsheetUrl).getSheetByName(totalWordName);
wordCountSheet = SpreadsheetApp.openByUrl(spreadsheetUrl).getSheetByName(wordCountName);
i++;
}
campaignWordSheet = SpreadsheetApp.openByUrl(spreadsheetUrl).insertSheet(campaignWordName);
totalWordSheet = SpreadsheetApp.openByUrl(spreadsheetUrl).insertSheet(totalWordName);
wordCountSheet = SpreadsheetApp.openByUrl(spreadsheetUrl).insertSheet(wordCountName);

campaignWordSheet.getRange(“R1C1”).setValue(“Analysis of Words in Search Query Report, By Campaign”);
wordCountSheet.getRange(“R1C1”).setValue(“Analysis of Search Query Performance by Words Count”);

if (campaignNameContains == “”) {
totalWordSheet.getRange(“R1C1”).setValue(“Analysis of Words in Search Query Report, By Account”);
} else {
totalWordSheet.getRange(“R1C1”).setValue(“Analysis of Words in Search Query Report, Over All Campaigns Containing ‘” + campaignNameContains + “‘”);
}

campaignWordSheet.getRange(“R2C1:R” + (campaignSearchWordsOutput.length+1) + “C” + campaignSearchWordsOutput[0].length).setValues(campaignSearchWordsOutput);
campaignWordSheet.getRange(“R3C3:R” + (campaignSearchWordsOutput.length+1) + “C” + (formatting.length+2)).setNumberFormats(campaignSearchWordsFormat);
totalWordSheet.getRange(“R2C1:R” + (totalSearchWordsOutput.length+1) + “C” + totalSearchWordsOutput[0].length).setValues(totalSearchWordsOutput);
totalWordSheet.getRange(“R3C2:R” + (totalSearchWordsOutput.length+1) + “C” + (formatting.length+1)).setNumberFormats(totalSearchWordsFormat);
wordCountSheet.getRange(“R2C1:R” + (wordLengthOutput.length+1) + “C” + wordLengthOutput[0].length).setValues(wordLengthOutput);
wordCountSheet.getRange(“R3C2:R” + (wordLengthOutput.length+1) + “C” + (formatting.length+1)).setNumberFormats(wordLengthFormat);

Logger.log(“Finished writing to spreadsheet.”);
}

 

3. Analise seus Termos de Pesquisa – Por Derek Martin. Revise seus termos de pesquisa e faça ajustes pela planilha do Google.

/**********************************************************************************************
* AdWords Account Management — Review Search Queries & Post Adjustments via Google Docs.
* Version 1.0
* Created By: Derek Martin
* DerekMartinLA.com & MixedMarketingArtist.com
*********************************************************************************************/

var GOOGLE_DOC_URL = “put your url here”;
var START_DATE = ‘20150401’;
var END_DATE = ‘20150415’;

function main() {
var results = runQueryReport();
modifySpreadSheet(results);
}

// check a query for whether the keyword exists in the account
// returns true or false

function keywordExists(keyword) {
var kw = keyword;

if (kw != null) {
kwIter = AdWordsApp.keywords().withCondition(“Text = \'”+kw+”\'”).withCondition(“Status = ENABLED”).get();

var exists = kwIter.totalNumEntities() > 0 ? true : false;
return exists;
}
}

function runQueryReport() {

var listOfQueries = [];

var report = AdWordsApp.report(
‘SELECT Query, CampaignName, AdGroupName, ConversionsManyPerClick, ConversionValue, Cost, AverageCpc, Clicks, Impressions, Ctr, ConversionRateManyPerClick ‘ +
‘FROM SEARCH_QUERY_PERFORMANCE_REPORT ‘ +
‘WHERE CampaignName does_not_contain Shopping ‘ +
‘DURING ‘ + START_DATE + ‘,’ + END_DATE +’ ‘);

var rows = report.rows();

while (rows.hasNext()) {
var row = rows.next();

var query = row[‘Query’];
var campaign= row[‘CampaignName’];
var adgroup = row[‘AdGroupName’];
var conversions = row[‘ConversionsManyPerClick’];
var conversionValue = parseFloat(row[‘ConversionValue’]).toPrecision(2);
var cost = parseFloat(row[‘Cost’]).toPrecision(2);
var roas = conversionValue / cost;
var averageCpc = row[‘AverageCpc’];
var clicks = row[‘Clicks’];
var impressions = row[‘Impressions’];
var ctr = row[‘Ctr’];
var conversionRate = row[‘ConversionRateManyPerClick’];

if (query.length < 20) {
var keyword_exists = keywordExists(query);
} else {
var keyword_exists = false;
}

var queryResult = new queryData(query, campaign, adgroup, conversions, conversionValue,cost, roas,averageCpc, clicks, impressions, ctr, conversionRate, keyword_exists);

listOfQueries.push(queryResult);

} // end of report run

return listOfQueries;

}

function queryData(query, campaign, adgroup, conversions, conversionValue, cost, roas, averageCpc, clicks, impressions, ctr, conversionRate, exists ) {
this.query = query;
this.campaign = campaign;
this.adgroup = adgroup;
this.conversions = conversions;
this.conversionValue = conversionValue;
this.cost = cost;
this.roas = roas;
this.averageCpc = averageCpc;
this.clicks = clicks;
this.impressions = impressions;
this.ctr = ctr;
this.conversionRate = conversionRate;
this.exists = exists;
} // end of productData

function modifySpreadSheet(results) {

var queryResults = results;

var querySS = SpreadsheetApp.openByUrl(GOOGLE_DOC_URL);

var sheet = querySS.getActiveSheet();

var columnNames = [“Query”, “In Account”, “Campaign”, “Ad Group”, “Conversions”, “Conversion Value”, “Cost”, “ROAS”, “Average CPC”,”Clicks”, “Impressions”, “Ctr”, “ConversionRate”];

var headersRange = sheet.getRange(1, 1, 1, columnNames.length);

headersRange.setFontWeight(“bold”);
headersRange.setFontSize(12);
headersRange.setBorder(false, false, true, false, false, false);

for (i = 0; i < queryResults.length; i++) {
headersRange.setValues([columnNames]);

var query = queryResults[i].query;
var exists = (queryResults[i].exists == true) ? “Added” : “Not Added”;
var campaign = queryResults[i].campaign;
var adgroup = queryResults[i].adgroup;
var conversions = queryResults[i].conversions;
var conversionValue = queryResults[i].conversionValue;
var cost = queryResults[i].cost;
var roas = (isNaN(queryResults[i].roas)) ? 0.00 : queryResults[i].roas;
var averageCpc = queryResults[i].averageCpc;
var clicks = queryResults[i].clicks;
var impressions = queryResults[i].impressions;
var ctr = queryResults[i].ctr;
var conversionRate = queryResults[i].conversionRate;

sheet.appendRow([query, exists, campaign, adgroup, conversions, conversionValue, cost, roas, averageCpc, clicks, impressions, ctr, conversionRate]);
}

sheet.getRange(“A2:M”).setFontSize(12);
sheet.getRange(“E:E”).setNumberFormat(“0”);
sheet.getRange(“F:G”).setNumberFormat(“$0.00”);
sheet.getRange(“H:H”).setNumberFormat(“0.00”);
sheet.getRange(“I:I”).setNumberFormat(“$0.00”);

sheet.getRange(“J:K”).setNumberFormat(“0.00”);
sheet.getRange(“A2:M”)
.sort({column: 5, ascending: false});
sheet.getRange(“A:D”).setVerticalAlignment(“middle”);
sheet.getRange(“A:D”).setHorizontalAlignment(“center”);
}

// Helper functions
function warn(msg) {
Logger.log(‘WARNING: ‘+msg);
}

function info(msg) {
Logger.log(msg);
}

 

4. Lista de palavras-chave negativas – Por Google Ads. Com esses 2 scripts você pode criar uma nova lista de palavras-chave negativa e apagar os termos que estão sendo compartilhados das outras listas de palavras-chave.

Construa uma nova lista de palavras-chave negativas e adicione-a a uma campanha

function addNegativeKeywordListToCampaign() {
var NEGATIVE_KEYWORD_LIST_NAME = ‘INSERT_LIST_NAME_HERE’;
var CAMPAIGN_NAME = ‘INSERT_CAMPAIGN_NAME_HERE’;

var negativeKeywordListOperator =
AdWordsApp.newNegativeKeywordListBuilder()
.withName(NEGATIVE_KEYWORD_LIST_NAME)
.build();

if (negativeKeywordListOperator.isSuccessful()) {
var negativeKeywordList = negativeKeywordListOperation.getResult();
negativeKeywordList.addKeywords(
‘broad match keyword’,
‘”phrase match keyword”‘,
‘[exact match keyword]’
);

var campaign = AdWordsApp.campaigns()
.withCondition(‘Name = “‘ + CAMPAIGN_NAME + ‘”‘)
.get();
campaign.addNegativeKeywordList(negativeKeywordList);
} else {
Logger.log(‘Could not add Negative Keyword List.’);
}
}

Remover todas as palavras-chave negativas compartilhadas em uma lista de palavras-chave negativas

function removeAllNegativeKeywordsFromList() {
var NEGATIVE_KEYWORD_LIST_NAME = ‘INSERT_LIST_NAME_HERE’;

var negativeKeywordListIterator =
AdWordsApp.negativeKeywordLists()
.withCondition(‘Name = “‘ + NEGATIVE_KEYWORD_LIST_NAME + ‘”‘)
.get();

if (negativeKeywordListIterator.totalNumEntities() == 1) {
var negativeKeywordList = negativeKeywordListIterator.next();
var sharedNegativeKeywordIterator =
negativeKeywordList.negativeKeywords().get();

var sharedNegativeKeywords = [];

while (sharedNegativeKeywordIterator.hasNext()) {
sharedNegativeKeywords.push(sharedNegativeKeywordIterator.next());
}

for (var i = 0; i < sharedNegativeKeywords.length; i++) {
sharedNegativeKeywords[i].remove();
}
}
}

 

5. Palavras-chave negativas – Por Google Ads. Adicione e exporte palavras-chave de suas campanhas e grupos de anúncios com esse script do Google Ads. Utilize-o caso não queira utilizar a plataforma do Google Ads.

Adicione palavras-chave negativas a uma campanha

function addNegativeKeywordToCampaign() {
var campaignIterator = AdWordsApp.campaigns()
.withCondition(‘Name = “INSERT_CAMPAIGN_NAME_HERE”‘)
.get();
if (campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
campaign.createNegativeKeyword(‘[Budget hotels]’);
}
}

 

Obter palavras-chave negativas em uma campanha

function getNegativeKeywordForCampaign() {
var campaignIterator = AdWordsApp.campaigns()
.withCondition(‘Name = “INSERT_CAMPAIGN_NAME_HERE”‘)
.get();
if (campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
var negativeKeywordIterator = campaign.negativeKeywords().get();
while (negativeKeywordIterator.hasNext()) {
var negativeKeyword = negativeKeywordIterator.next();
Logger.log(‘Text: ‘ + negativeKeyword.getText() + ‘, MatchType: ‘ +
negativeKeyword.getMatchType());
}
}
}

 

Adicione uma palavra-chave negativa a um grupo de anúncios

function addNegativeKeywordToAdGroup() {
// If you have multiple ad groups with the same name, this snippet will
// pick an arbitrary matching ad group each time. In such cases, just
// filter on the campaign name as well:
//
// AdWordsApp.adGroups()
// .withCondition(‘Name = “INSERT_ADGROUP_NAME_HERE”‘)
// .withCondition(‘CampaignName = “INSERT_CAMPAIGN_NAME_HERE”‘)
var adGroupIterator = AdWordsApp.adGroups()
.withCondition(‘Name = “INSERT_ADGROUP_NAME_HERE”‘)
.get();
if (adGroupIterator.hasNext()) {
var adGroup = adGroupIterator.next();
adGroup.createNegativeKeyword(‘[Budget hotels]’);
}
}

 

Obter palavras-chave negativas em um grupo de anúncios

function getNegativeKeywordForAdGroup() {
// If you have multiple ad groups with the same name, this snippet will
// pick an arbitrary matching ad group each time. In such cases, just
// filter on the campaign name as well:
//
// AdWordsApp.adGroups()
// .withCondition(‘Name = “INSERT_ADGROUP_NAME_HERE”‘)
// .withCondition(‘CampaignName = “INSERT_CAMPAIGN_NAME_HERE”‘)
var adGroupIterator = AdWordsApp.adGroups()
.withCondition(‘Name = “INSERT_ADGROUP_NAME_HERE”‘)
.get();
if (adGroupIterator.hasNext()) {
var adGroup = adGroupIterator.next();
var negativeKeywordIterator = adGroup.negativeKeywords().get();
while (negativeKeywordIterator.hasNext()) {
var negativeKeyword = negativeKeywordIterator.next();
Logger.log(‘Text: ‘ + negativeKeyword.getText() + ‘, MatchType: ‘ +
negativeKeyword.getMatchType());
}
}
}

 

6. Lista mestre negativa – Por Google Ads. Esse script é ideal caso você tenha uma conta de administrador e tenha várias outras contas sob sua gerência, assim, com você consegue expandir termos comuns que não são interessantes para buscas.

// Copyright 2015, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the “License”);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// //www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
* @name Master Negative List Script for AdWords manager accounts
*
* @overview The Master Negative List script for AdWords manager accounts
* applies negative keywords and placements from a spreadsheet to multiple
* campaigns in your account using shared keyword and placement lists. The
* script can process multiple AdWords accounts in parallel. See
* //developers.google.com/adwords/scripts/docs/solutions/mccapp-master-negative-list
* for more details.
*
* @author AdWords Scripts Team [[email protected]]
*
* @version 1.0.2
*
* @changelog
* – version 1.0.2
* – Added validation for external spreadsheet setup.
* – version 1.0.1
* – Improvements to time zone handling.
* – version 1.0
* – Released initial version.
*/

/**
* The URL of the tracking spreadsheet. This should be a copy of
* //goo.gl/i4q728
*/
var SPREADSHEET_URL = ‘INSERT_SPREADSHEET_URL_HERE’;

/**
* Keep track of the spreadsheet names for various criteria types, as well as
* the criteria type being processed.
*/
var CriteriaType = {
KEYWORDS: ‘Keywords’,
PLACEMENTS: ‘Placements’
};

/**
* The code to execute when running the script.
*/
function main() {
var config = readConfig();

var accountSelector = MccApp.accounts();
if (config.customerids.length > 0) {
accountSelector.withIds(config.customerids);
}
accountSelector.executeInParallel(‘processAccounts’, ‘postProcess’);
}

/**
* Process an account when processing multiple accounts under an AdWords manager
* account in parallel.
*
* @return {string} A JSON string that summarizes the number of keywords and
* placements synced, and the number of campaigns processed.
*/
function processAccounts() {
return JSON.stringify(syncMasterLists());
}

/**
* Callback method after processing accounts, when processing multiple accounts
* under an AdWords manager account in parallel.
*
* @param {Array.<MccApp.ExecutionResult>} results The execution results from
* the accounts that were processed by this script.
*/
function postProcess(results) {
var config = readConfig();
var emailParams = {
// Number of placements that were synced.
PlacementCount: 0,
// Number of keywords that were synced.
KeywordCount: 0,
// Summary of customers who were synced.
Customers: {
// How many customers were synced?
Success: 0,
// How many customers failed to sync?
Failure: 0,
// Details of each account processed. Contains 3 properties:
// CustomerId, CampaignCount, Status.
Details: []
}
};

for (var i = 0; i < results.length; i++) {
var customerResult = {
// The customer ID that was processed.
CustomerId: results[i].getCustomerId(),
// Number of campaigns that were synced.
CampaignCount: 0,
// Status of processing this account – OK / ERROR / TIMEOUT
Status: results[i].getStatus()
};

if (results[i].getStatus() == ‘OK’) {
var retval = JSON.parse(results[i].getReturnValue());
customerResult.CampaignCount = retval.CampaignCount;
if (emailParams.Customers.Success == 0) {
emailParams.KeywordCount = retval.KeywordCount;
emailParams.PlacementCount = retval.PlacementCount;
}
emailParams.Customers.Success++;
} else {
emailParams.Customers.Failure++;
}
emailParams.Customers.Details.push(customerResult);
}

var spreadsheet = validateAndGetSpreadsheet(SPREADSHEET_URL);

// Make sure the spreadsheet is using the account’s timezone.
spreadsheet.setSpreadsheetTimeZone(AdWordsApp.currentAccount().getTimeZone());
spreadsheet.getRangeByName(‘LastRun’).setValue(new Date());
spreadsheet.getRangeByName(‘CustomerId’).setValue(
AdWordsApp.currentAccount().getCustomerId());

sendEmail(config, emailParams);
}

/**
* Sends a summary email about the changes that this script made.
*
* @param {Object} config The configuration object.
* @param {Object} emailParams Contains details required to create the email
* body.
*/
function sendEmail(config, emailParams) {
var html = [];

html.push(‘<html>’,
‘<head></head>’,
‘<body>’,
“<table style=’font-family:Arial,Helvetica; ” +
‘border-collapse:collapse;font-size:10pt; ‘ +
“color:#444444; border: solid 1px #dddddd;’ ” +
“width=’600′ cellpadding=20>”,
‘<tr>’,
‘<td>’,
‘<p>Hello,</p>’,
‘<p>The Master Negative List script synced a total ‘ +
‘of <b>’ + emailParams.KeywordCount + ‘</b> ‘ +
‘keywords and <b>’ + emailParams.PlacementCount +
‘</b> placements. <b>’ +
(emailParams.Customers.Success +
emailParams.Customers.Failure) +
‘</b> accounts were processed, of which <b>’ +
emailParams.Customers.Success + ‘</b> ‘ +
‘succeeded, and <b>’ +
emailParams.Customers.Failure + ‘</b> failed. ‘ +
‘See the table below’ +
‘ for details.</p>’,
“<table border=’1′ width=’100%’ ” +
“style=’border-collapse: collapse; ” +
“border: solid 1px #dddddd;font-size:10pt;’>”,
‘<tr>’,
‘<th>CustomerId</th>’,
‘<th>Synced Campaigns</th>’,
‘<th>Status</th>’,
‘</tr>’
);

for (var i = 0; i < emailParams.Customers.Details.length; i++) {
var detail = emailParams.Customers.Details[i];
html.push(‘<tr>’,
‘<td>’ + detail.CustomerId + ‘</td>’,
‘<td>’ + detail.CampaignCount + ‘</td>’,
‘<td>’ + detail.Status + ‘</td>’,
‘</tr>’
);
}

html.push(‘</table>’,
‘<p>Cheers<br />AdWords Scripts Team</p>’,
‘</td>’,
‘</tr>’,
‘</table>’,
‘</body>’,
‘</html>’
);

if (config.email != ”) {
MailApp.sendEmail({
to: config.email,
subject: ‘Master Negative List Script’,
htmlBody: html.join(‘\n’)
});
}
}

/**
* Synchronizes the negative criteria list in an account with the master list
* in the user spreadsheet.
*
* @return {Object} A summary of the number of keywords and placements synced,
* and the number of campaigns to which these lists apply.
*/
function syncMasterLists() {
var config = readConfig();
var syncedCampaignCount = 0;

var keywordListDetails = syncCriteriaInNegativeList(config,
CriteriaType.KEYWORDS);
syncedCampaignCount = syncCampaignList(config, keywordListDetails.SharedList,
CriteriaType.KEYWORDS);

var placementListDetails = syncCriteriaInNegativeList(config,
CriteriaType.PLACEMENTS);
syncedCampaignCount = syncCampaignList(config,
placementListDetails.SharedList, CriteriaType.PLACEMENTS);

return {
‘CampaignCount’: syncedCampaignCount,
‘PlacementCount’: placementListDetails.CriteriaCount,
‘KeywordCount’: keywordListDetails.CriteriaCount
};
}

/**
* Synchronizes the list of campaigns covered by a negative list against the
* desired list of campaigns to be covered by the master list.
*
* @param {Object} config The configuration object.
* @param {AdWordsApp.NegativeKeywordList|AdWordsApp.ExcludedPlacementList}
* sharedList The shared negative criterion list to be synced against the
* master list.
* @param {String} criteriaType The criteria type for the shared negative list.
*
* @return {Number} The number of campaigns synced.
*/
function syncCampaignList(config, sharedList, criteriaType) {
var campaignIds = getLabelledCampaigns(config.label);
var totalCampaigns = Object.keys(campaignIds).length;

var listedCampaigns = sharedList.campaigns().get();

var campaignsToRemove = [];

while (listedCampaigns.hasNext()) {
var listedCampaign = listedCampaigns.next();
if (listedCampaign.getId() in campaignIds) {
delete campaignIds[listedCampaign.getId()];
} else {
campaignsToRemove.push(listedCampaign);
}
}

// Anything left over in campaignIds starts a new list.
var campaignsToAdd = AdWordsApp.campaigns().withIds(
Object.keys(campaignIds)).get();
while (campaignsToAdd.hasNext()) {
var campaignToAdd = campaignsToAdd.next();

if (criteriaType == CriteriaType.KEYWORDS) {
campaignToAdd.addNegativeKeywordList(sharedList);
} else if (criteriaType == CriteriaType.PLACEMENTS) {
campaignToAdd.addExcludedPlacementList(sharedList);
}
}

for (var i = 0; i < campaignsToRemove.length; i++) {
if (criteriaType == CriteriaType.KEYWORDS) {
campaignsToRemove[i].removeNegativeKeywordList(sharedList);
} else if (criteriaType == CriteriaType.PLACEMENTS) {
campaignsToRemove[i].removeExcludedPlacementList(sharedList);
}
}

return totalCampaigns;
}

/**
* Gets a list of campaigns having a particular label.
*
* @param {String} labelText The label text.
*
* @return {Array.<Number>} An array of campaign IDs having the specified
* label.
*/
function getLabelledCampaigns(labelText) {
var campaignIds = {};

if (labelText != ”) {
var label = getLabel(labelText);
var campaigns = label.campaigns().withCondition(
‘Status in [ENABLED, PAUSED]’).get();
} else {
var campaigns = AdWordsApp.campaigns().withCondition(
‘Status in [ENABLED, PAUSED]’).get();
}

while (campaigns.hasNext()) {
var campaign = campaigns.next();
campaignIds[campaign.getId()] = 1;
}
return campaignIds;
}

/**
* Gets a label with the specified label text.
*
* @param {String} labelText The label text.
*
* @return {AdWordsApp.Label} The label text.
*/
function getLabel(labelText) {
var labels = AdWordsApp.labels().withCondition(
“Name='” + labelText + “‘”).get();
if (labels.totalNumEntities() == 0) {
var message = Utilities.formatString(‘Label named %s is missing in your ‘ +
‘account. Make sure the label exists in the account, and is applied ‘ +
‘to campaigns and adgroups you wish to process.’, labelText);
throw (message);
}

return labels.next();
}

/**
* Synchronizes the criteria in a shared negative criteria list with the user
* spreadsheet.
*
* @param {Object} config The configuration object.
* @param {String} criteriaType The criteria type for the shared negative list.
*
* @return {Object} A summary of the synced negative list, and the number of
* criteria that were synced.
*/
function syncCriteriaInNegativeList(config, criteriaType) {
var criteriaFromSheet = loadCriteria(criteriaType);
var totalCriteriaCount = Object.keys(criteriaFromSheet).length;

var sharedList = null;
var listName = config.listname[criteriaType];

sharedList = createNegativeListIfRequired(listName, criteriaType);

var negativeCriteria = null;

try {
if (criteriaType == CriteriaType.KEYWORDS) {
negativeCriteria = sharedList.negativeKeywords().get();
} else if (criteriaType == CriteriaType.PLACEMENTS) {
negativeCriteria = sharedList.excludedPlacements().get();
}
} catch (e) {
Logger.log(‘Failed to retrieve shared list. Error says ‘ + e);
if (AdWordsApp.getExecutionInfo().isPreview()) {
var message = Utilities.formatString(‘The script cannot create the ‘ +
‘negative %s list in preview mode. Either run the script without ‘ +
‘preview, or create a negative %s list with name “%s” manually ‘ +
‘before previewing the script.’, criteriaType, criteriaType,
listName);
Logger.log(message);
}
throw e;
}

var criteriaToDelete = [];

while (negativeCriteria.hasNext()) {
var negativeCriterion = negativeCriteria.next();
var key = null;

if (criteriaType == CriteriaType.KEYWORDS) {
key = negativeCriterion.getText();
} else if (criteriaType == CriteriaType.PLACEMENTS) {
key = negativeCriterion.getUrl();
}

if (key in criteriaFromSheet) {
// Nothing to do with this criteria. Remove it from loaded list.
delete criteriaFromSheet[key];
} else {
// This criterion is not in the sync list. Mark for deletion.
criteriaToDelete.push(negativeCriterion);
}
}

// Whatever left in the sync list are new items.
if (criteriaType == CriteriaType.KEYWORDS) {
sharedList.addNegativeKeywords(Object.keys(criteriaFromSheet));
} else if (criteriaType == CriteriaType.PLACEMENTS) {
sharedList.addExcludedPlacements(Object.keys(criteriaFromSheet));
}

for (var i = 0; i < criteriaToDelete.length; i++) {
criteriaToDelete[i].remove();
}

return {
‘SharedList’: sharedList,
‘CriteriaCount’: totalCriteriaCount,
‘Type’: criteriaType
};
}

/**
* Creates a shared negative criteria list if required.
*
* @param {string} listName The name of shared negative criteria list.
* @param {String} listType The criteria type for the shared negative list.
*
* @return {AdWordsApp.NegativeKeywordList|AdWordsApp.ExcludedPlacementList} An
* existing shared negative criterion list if it already exists in the
* account, or the newly created list if one didn’t exist earlier.
*/
function createNegativeListIfRequired(listName, listType) {
var negativeListSelector = null;
if (listType == CriteriaType.KEYWORDS) {
negativeListSelector = AdWordsApp.negativeKeywordLists();
} else if (listType == CriteriaType.PLACEMENTS) {
negativeListSelector = AdWordsApp.excludedPlacementLists();
}
var negativeListIterator = negativeListSelector.withCondition(
“Name = ‘” + listName + “‘”).get();

if (negativeListIterator.totalNumEntities() == 0) {
var builder = null;

if (listType == CriteriaType.KEYWORDS) {
builder = AdWordsApp.newNegativeKeywordListBuilder();
} else if (listType == CriteriaType.PLACEMENTS) {

builder = AdWordsApp.newExcludedPlacementListBuilder();
}

var negativeListOperation = builder.withName(listName).build();
return negativeListOperation.getResult();
} else {
return negativeListIterator.next();
}
}

/**
* Loads a list of criteria from the user spreadsheet.
*
* @param {string} sheetName The name of shared negative criteria list.
*
* @return {Object} A map of the list of criteria loaded from the spreadsheet.
*/
function loadCriteria(sheetName) {
var spreadsheet = validateAndGetSpreadsheet(SPREADSHEET_URL);
var sheet = spreadsheet.getSheetByName(sheetName);
var values = sheet.getRange(‘B4:B’).getValues();

var retval = {};
for (var i = 0; i < values.length; i++) {
var keyword = values[i][0].toString().trim();
if (keyword != ”) {
retval[keyword] = 1;
}
}
return retval;
}

/**
* Loads a configuration object from the spreadsheet.
*
* @return {Object} A configuration object.
*/
function readConfig() {
var spreadsheet = validateAndGetSpreadsheet(SPREADSHEET_URL);
var values = spreadsheet.getRangeByName(‘ConfigurationValues’).getValues();

var config = {
‘label’: values[0][0],
‘listname’: {
},
‘email’: values[3][0],
‘customerids’: extractCustomerIds(values[4][0])
};
config.listname[CriteriaType.KEYWORDS] = values[1][0];
config.listname[CriteriaType.PLACEMENTS] = values[2][0];
return config;
}

/**
* Extracts customerIds from a comma separated list.
*
* @param {string} data the input.
* @return {Array.<number>} A list of customer IDs.
*/
function extractCustomerIds(data) {
var retval = [];

var splits = data.split(‘,’);

for (var i = 0; i < splits.length; i++) {
var split = splits[i];
split = split.trim().replace(/-/g, ”).replace(/^\s+|\s+$/g, ”);
if (split) {
if (isNaN(split)) {
Logger.log(‘Invalid customer ID found in spreadsheet: ‘ + split);
} else {
var customerId = parseInt(split).toFixed(0);
retval.push(customerId);
}
}
}
return retval;
}

/**
* DO NOT EDIT ANYTHING BELOW THIS LINE.
* Please modify your spreadsheet URL at the top of the file only.
*/

/**
* Validates the provided spreadsheet URL and email address
* to make sure that they’re set up properly. Throws a descriptive error message
* if validation fails.
*
* @param {string} spreadsheeturl The URL of the spreadsheet to open.
* @return {Spreadsheet} The spreadsheet object itself, fetched from the URL.
* @throws {Error} If the spreadsheet URL or email hasn’t been set
*/
function validateAndGetSpreadsheet(spreadsheeturl) {
if (spreadsheeturl == ‘INSERT_SPREADSHEET_URL_HERE’) {
throw new Error(‘Please specify a valid Spreadsheet URL. You can find’ +
‘ a link to a template in the associated guide for this script.’);
}
var spreadsheet = SpreadsheetApp.openByUrl(spreadsheeturl);
return spreadsheet;
}

 

Como Configurar

 

7. Palavras-chave – Por Google Ads. Os scripts de palavras-chave do Google Ads permitem que você adicione/pause palavras-chave à um grupo de anúncios. Além disso, é possível que você extraia todas as palavras-chave de um grupo de anúncios e seus dados também.

Adicione uma palavra-chave a um grupo de anúncios existente

function addKeyword() {
// If you have multiple adGroups with the same name, this snippet will
// pick an arbitrary matching ad group each time. In such cases, just
// filter on the campaign name as well:
//
// AdWordsApp.adGroups()
// .withCondition(‘Name = “INSERT_ADGROUP_NAME_HERE”‘)
// .withCondition(‘CampaignName = “INSERT_CAMPAIGN_NAME_HERE”‘)
var adGroupIterator = AdWordsApp.adGroups()
.withCondition(‘Name = “INSERT_ADGROUP_NAME_HERE”‘)
.get();
if (adGroupIterator.hasNext()) {
var adGroup = adGroupIterator.next();

adGroup.newKeywordBuilder()
.withText(‘Hello world’)
.withCpc(1.25) // Optional
.withFinalUrl(‘//www.example.com’) // Optional
.build();

// KeywordBuilder has a number of other options. For more details see
// //developers.google.com/adwords/scripts/docs/reference/adwordsapp/adwordsapp_keywordbuilder
}
}

 

Pausar uma palavra-chave existente em um grupo de anúncios

function pauseKeywordInAdGroup() {
var adGroupIterator = AdWordsApp.adGroups()
.withCondition(‘Name = “INSERT_ADGROUP_NAME_HERE”‘)
.get();
if (adGroupIterator.hasNext()) {
var adGroup = adGroupIterator.next();
var keywordIterator = adGroup.keywords()
.withCondition(‘Text=”INSERT_KEYWORDS_HERE”‘).get();
while (keywordIterator.hasNext()) {
var keyword = keywordIterator.next();
keyword.pause();
}
}
}

 

Obter todas as palavras-chave em um grupo de anúncios

function getKeywordsInAdGroup() {
var keywordIterator = AdWordsApp.keywords()
.withCondition(‘AdGroupName = “INSERT_ADGROUP_NAME_HERE”‘)
.get();
if (keywordIterator.hasNext()) {
while (keywordIterator.hasNext()) {
var keyword = keywordIterator.next();
Logger.log(formatKeyword(keyword));
}
}
}

function formatKeyword(keyword) {
return ‘Text : ‘ + keyword.getText() + ‘\n’ +
‘Match type : ‘ + keyword.getMatchType() + ‘\n’ +
‘CPC : ‘ + keyword.bidding().getCpc() + ‘\n’ +
‘Final URL : ‘ + keyword.urls().getFinalUrl() + ‘\n’ +
‘Approval Status : ‘ + keyword.getApprovalStatus() + ‘\n’ +
‘Enabled : ‘ + keyword.isEnabled() + ‘\n’;
}

 

Obter estatísticas de todas as palavras-chave em um grupo de anúncios

function getKeywordStats() {
var adGroupIterator = AdWordsApp.adGroups()
.withCondition(‘Name = “INSERT_ADGROUP_NAME_HERE”‘)
.get();
if (adGroupIterator.hasNext()) {
var adGroup = adGroupIterator.next();
var keywordIterator = adGroup.keywords().get();
while (keywordIterator.hasNext()) {
var keyword = keywordIterator.next();
// You can also request reports for pre-defined date ranges. See
// //developers.google.com/adwords/api/docs/guides/awql,
// DateRangeLiteral section for possible values.
var stats = keyword.getStatsFor(‘LAST_MONTH’);
Logger.log(adGroup.getName() + ‘, ‘ + keyword.getText() + ‘, ‘ +
stats.getClicks() + ‘, ‘ + stats.getImpressions());
}
}
}



Mais de Rotamáxima Marketing Digital

Procurar conteúdo

Eventos

Fevereiro

25fev(fev 25)00:0027(fev 27)00:00Traffic & Conversion Summit

Março

08mar(mar 8)00:0009(mar 9)00:00ProXXIma

08mar(mar 8)00:0017(mar 17)00:00SXSW Conference & Festivals

27mar(mar 27)00:0029(mar 29)00:00Conversion XL Live

Maio

30mai(mai 30)00:0031(mai 31)00:00VTexDay

Agosto

28ago(ago 28)00:0029(ago 29)00:00Expo Fórum Digitalks 2019

Setembro

03set(set 3)00:0006(set 6)00:00Inbound 2019

X