Le marketing numérique et le PPC évoluent incroyablement rapidement. Cependant, pour toutes les innovations technologiques…
Surveiller Les Liens Rompus À L’Aide De Scripts De Niveau MCC
Pour ceux qui ne le savaient pas, ils sont enfin là sous forme bêta. Les scripts AdWords sont désormais disponibles au niveau MCC. Alors, quoi de neuf avec les scripts de niveau MCC? Tous les détails se trouvent sur la page des développeurs Google, mais voici un résumé. Vous pouvez désormais lancer des sélecteurs sur les comptes en utilisant l’objet MccApp. Le filtrage par statistiques est le même que les autres sélecteurs, mais maintenant vous l’exécutez au niveau du compte. Lorsque vous travaillez sur chaque compte, une fois que vous avez défini le compte sur lequel vous souhaitez travailler à l’aide de MccApp.select (), tout fonctionne comme avant.
La nouvelle fonction dont vous voudrez probablement profiter est executeInParallel () qui vous permet d’exécuter le même code sur jusqu’à 50 comptes en même temps. Vous pouvez donc lancer un script de reporting pour l’exécuter sur tous vos comptes, puis collecter les résultats et envoyer un seul e-mail ou le stocker sur une seule feuille de calcul. De plus, les scripts peuvent maintenant fonctionner jusqu’à 60 minutes en utilisant cette méthode car vous obtenez 30 minutes de temps d’exécution pour exécuter le code sur chaque compte et 30 minutes pour collecter les résultats de la fonction de rappel.
Pour vous aider à démarrer avec le nouvel objet MccApp, j’ai pensé que je prendrais l’un de mes articles les plus populaires et le réécrirais pour qu’il fonctionne au niveau MCC. Trouver des URL cassées dans votre compte est un excellent exemple de la façon dont vous pouvez tirer parti de la nouvelle fonction executeInParallel () pour améliorer la surveillance de votre MCC.
Ce script fonctionne de manière très similaire au script précédent, mais a quelques fonctionnalités ajoutées. Ce script vérifiera tous vos URL de mots clés et d’annonces une fois par jour. Lorsque vous installez ce script, vous devez le programmer pour qu’il s’exécute toutes les heures au cas où un compte volumineux ne pourrait pas être traité dans le délai imparti, il peut reprendre là où il s’était arrêté et continuer le traitement. Il contrôle cela en interne à l’aide d’étiquettes.
De plus, les résultats de ce script sont stockés dans une nouvelle feuille de calcul pour chaque exécution. J’ai eu des problèmes avec le dernier où le script écrasait les valeurs dans la feuille de calcul avant d’avoir la chance de les regarder. Cela élimine ce problème. La feuille de calcul est accessible à partir d’un e-mail récapitulatif qui ressemble à ceci, chaque ligne contenant un lien vers l’onglet de la feuille de calcul avec les résultats de ce compte.
Il existe quelques autres fonctionnalités telles que la possibilité de vous avertir lorsque des erreurs se produisent, de signaler les redirections et de définir le nombre de codes de réponse que vous recherchez.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 |
/****************************************** * Monitor Broken Links Using MCC Level Scripts * Version 1.5 * Changelog v1.5 * - Additional fixes from copy and paste errors * Changelog v1.4 * - Fixed INVALID_QUERY error * Changelog v1.3 * - Added previous version of report api to script until * I update my urls. * Changelog v1.2 * - Fixing INVALID_PREDICATE_ENUM_VALUE * Changelog v1.1 * - Stopped timeouts * Created By: Russ Savage * FreeAdWordsScripts.com ******************************************/ var SCRIPT_NAME = 'Broken Url Checker'; var LOG_LEVEL = 'error'; //change this to debug if you want more logging var NOTIFY = ['']; var SPREADSHEET_PREFIX = 'Broken Url Details'; // A timestamp is appended var NOTIFY_ON_ERROR = ['']; var STRIP_QUERY_STRING = true; //Drop everything after the ? in the url to speed things up var REPORT_ON_REDIRECTS = true; //If you want to be able to track 301s and 302, turn this on var VALID_RESPONSE_CODES = [200,301,302]; var URLS_CHECKED_FILE_NAME = 'UrlsAlreadyChecked-'+AdWordsApp.currentAccount().getCustomerId()+'.json'; var DONE_LABEL_PREFIX = 'All Urls Checked - '; function main() { MccApp.accounts().withLimit(50).executeInParallel('checkUrls', 'reportResults'); } function checkUrls() { try { debug('Processing account: '+AdWordsApp.currentAccount().getName()); debug('Checking to see if we finished processing for today.'); var dateStr = Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), 'yyyy-MM-dd'); var finishedLabelName = DONE_LABEL_PREFIX+dateStr; var alreadyDone = AdWordsApp.labels().withCondition("Name = '"+finishedLabelName+"'").get().hasNext(); if(alreadyDone) { info('All urls have been checked for today.'); return ''; } var labelIter = AdWordsApp.labels().withCondition("Name STARTS_WITH '"+DONE_LABEL_PREFIX+"'").get(); while(labelIter.hasNext()) { labelIter.next().remove(); } debug('Checking for previous urls.'); var urlsAlreadyChecked = readValidUrlsFromJSON(); info('Found '+Object.keys(urlsAlreadyChecked).length+' urls already checked.'); var toReportKeywords = []; var toReportAds = []; var didExitEarly = false; var keywordUrls = getKeywordUrls(); for(var key in keywordUrls) { var kwRow = keywordUrls[key]; var final_urls = kwRow.FinalUrls.split(';'); for(var i in final_urls) { var url = cleanUrl(final_urls[i]); verifyUrl(kwRow,url,urlsAlreadyChecked,toReportKeywords); if(shouldExitEarly()) { didExitEarly = true; break; } } } if(!didExitEarly) { var adUrls = getAdUrls(); for(var i in adUrls) { var adRow = adUrls[i]; if(adRow.CreativeFinalUrls) { var final_urls = adRow.CreativeFinalUrls.split(';'); for(var x in final_urls) { var url = cleanUrl(final_urls[x]); verifyUrl(adRow,url,urlsAlreadyChecked,toReportAds); } } if(shouldExitEarly()) { didExitEarly = true; break; } } } var returnData = { accountId : AdWordsApp.currentAccount().getCustomerId(), accountName : AdWordsApp.currentAccount().getName(), uniqueUrlsChecked : Object.keys(urlsAlreadyChecked).length, brokenKeywords : toReportKeywords, brokenAds : toReportAds, didExitEarly : didExitEarly }; if(didExitEarly) { writeValidUrlsToJSON(urlsAlreadyChecked); } else { AdWordsApp.createLabel(finishedLabelName, 'Label created by '+SCRIPT_NAME, '#C0C0C0'); writeValidUrlsToJSON({}); } return JSON.stringify(returnData); } catch(e) { // This error handling helps notify you when things don't work out well. error(e); if(MailApp.getRemainingDailyQuota() >= NOTIFY_ON_ERROR.length) { var acctName = AdWordsApp.currentAccount().getName(); var acctId = AdWordsApp.currentAccount().getCustomerId(); for(var i in NOTIFY_ON_ERROR) { info('Sending mail to: '+NOTIFY_ON_ERROR[i]); MailApp.sendEmail(NOTIFY_ON_ERROR[i], 'ERROR: '+SCRIPT_NAME+' - '+acctName+' - ('+acctId+')', e); } } else { error('Out of email quota for the day. Sending a carrier pigeon.'); } return ''; } function shouldExitEarly() { return (AdWordsApp.getExecutionInfo().getRemainingTime() < 60); } function verifyUrl(row,url,urlsAlreadyChecked,toReport) { if(!urlsAlreadyChecked[url]) { info('Checking url: ' + url); var urlCheckResults = checkUrl(url); if(!urlCheckResults.isValid) { row['cleanUrl'] = url; row['responseCode'] = urlCheckResults.responseCode; toReport.push(row); } urlsAlreadyChecked[url] = urlCheckResults; } else { if(!urlsAlreadyChecked[url].isValid) { row['cleanUrl'] = url; row['responseCode'] = urlsAlreadyChecked[url].responseCode; toReport.push(row); } } } function checkUrl(url) { var retVal = { responseCode : -1, isValid: false }; var httpOptions = { muteHttpExceptions:true, followRedirects:(!REPORT_ON_REDIRECTS) }; try { retVal.responseCode = UrlFetchApp.fetch(url, httpOptions).getResponseCode(); retVal.isValid = isValidResponseCode(retVal.responseCode); } catch(e) { warn(e.message); //Something is wrong here, we should know about it. retVal.isValid = false; } return retVal; } function isValidResponseCode(resp) { return (VALID_RESPONSE_CODES.indexOf(resp) >= 0); } //Clean the url of query strings and valuetrack params function cleanUrl(url) { if(STRIP_QUERY_STRING) { if(url.indexOf('?')>=0) { url = url.split('?')[0]; } } if(url.indexOf('{') >= 0) { //Let's remove the value track parameters url = url.replace(/\{[^\}]*\}/g,''); } return url; } //Use the reporting API to pull this information because it is super fast. //The documentation for this is here: http://goo.gl/IfMb31 function getKeywordUrls() { var OPTIONS = { includeZeroImpressions : true }; var cols = ['CampaignId','CampaignName', 'AdGroupId','AdGroupName', 'Id','Criteria','KeywordMatchType', 'IsNegative','FinalUrls','Impressions']; var report = 'KEYWORDS_PERFORMANCE_REPORT'; var query = ['select',cols.join(','),'from',report, 'where CampaignStatus = ENABLED', 'and AdGroupStatus = ENABLED', 'and Status = ENABLED', 'during','LAST_7_DAYS'].join(' '); var results = {}; var reportIter = AdWordsApp.report(query, OPTIONS).rows(); while(reportIter.hasNext()) { var row = reportIter.next(); if(row.IsNegative === 'true') { continue; } if(!row.FinalUrls) { continue; } if(row.KeywordMatchType === 'Exact') { row.Criteria = ['[',row.Criteria,']'].join(''); } else if(row.Criteria === 'Phrase') { row.Criteria = ['"',row.Criteria,'"'].join(''); } var rowKey = [row.CampaignId,row.AdGroupId,row.Id].join('-'); results[rowKey] = row; } return results; } //Use the reporting API to pull this information because it is super fast. //The documentation for this is here: http://goo.gl/8RHTBj function getAdUrls() { var OPTIONS = { includeZeroImpressions : true }; var cols = ['CampaignId','CampaignName', 'AdGroupId','AdGroupName', 'AdType', 'Id','Headline','Description1','Description2','DisplayUrl', 'CreativeFinalUrls','Impressions']; var report = 'AD_PERFORMANCE_REPORT'; var query = ['select',cols.join(','),'from',report, 'where CampaignStatus = ENABLED', 'and AdGroupStatus = ENABLED', 'and Status = ENABLED', 'during','TODAY'].join(' '); var results = {}; var reportIter = AdWordsApp.report(query, OPTIONS).rows(); while(reportIter.hasNext()) { var row = reportIter.next(); if(!row.CreativeFinalUrls) { continue; } var rowKey = [row.CampaignId,row.AdGroupId,row.Id].join('-'); results[rowKey] = row; } return results; } //This function quickly writes the url data to a file //that can be loaded again for the next run function writeValidUrlsToJSON(toWrite) { var file = getFile(URLS_CHECKED_FILE_NAME,false); file.setContent(JSON.stringify(toWrite)); } //And this loads that stored file and converts it to an object function readValidUrlsFromJSON() { var file = getFile(URLS_CHECKED_FILE_NAME,false); var fileData = file.getBlob().getDataAsString(); if(fileData) { return JSON.parse(fileData); } else { return {}; } } } //This is the callback function that collects all the data from the scripts //that were run in parallel on each account. More details can be found here: // http://goo.gl/BvOPZo function reportResults(responses) { var summaryEmailData = []; var dateTimeStr = Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), 'yyyy-MM-dd HH:m:s'); var spreadsheetName = SPREADSHEET_PREFIX+' - '+dateTimeStr; for(var i in responses) { if(!responses[i].getReturnValue()) { continue; } var res = JSON.parse(responses[i].getReturnValue()); var sheetUrl = writeResultsToSpreadsheet(res,spreadsheetName); summaryEmailData.push({accountId:res.accountId, accountName:res.accountName, didExitEarly:res.didExitEarly, uniqueUrlsChecked:res.uniqueUrlsChecked, numBrokenKeywords:res.brokenKeywords.length, numBrokenAds:res.brokenAds.length, sheetUrl: sheetUrl}); } if(summaryEmailData.length > 0) { sendSummaryEmail(summaryEmailData); } function writeResultsToSpreadsheet(res,name) { var file = getFile(name,true); var spreadsheet; var maxRetries = 0; while(maxRetries < 3) { try { spreadsheet = SpreadsheetApp.openById(file.getId()); break; } catch(e) { maxRetries++; Utilities.sleep(1000); } } if(!spreadsheet) { throw 'Could not open file: '+name; } if(spreadsheet.getSheetByName('Sheet1')) { spreadsheet.getSheetByName('Sheet1').setName(res.accountId); } var sheet = spreadsheet.getSheetByName(res.accountId); if(!sheet) { sheet = spreadsheet.insertSheet(res.accountId, spreadsheet.getSheets().length); } var toWrite = [['Type','Clean Url','Response Code','Campaign Name','AdGroup Name','Text','Full Url']]; for(var i in res.brokenKeywords) { var row = res.brokenKeywords[i]; toWrite.push(['Keyword', row.cleanUrl, row.responseCode, row.CampaignName, row.AdGroupName, row.Criteria, row.FinalUrls]); } for(var i in res.brokenAds) { var row = res.brokenAds[i]; toWrite.push([row.AdType, row.cleanUrl, row.responseCode, row.CampaignName, row.AdGroupName, (row.Headline) ? [row.Headline,row.Description1,row.Description2,row.DisplayUrl].join('|') : '', row.CreativeFinalUrls]); } var lastRow = sheet.getLastRow(); var numRows = sheet.getMaxRows(); if((numRows-lastRow) < toWrite.length) { sheet.insertRowsAfter(lastRow,toWrite.length-numRows+lastRow); } var range = sheet.getRange(lastRow+1,1,toWrite.length,toWrite[0].length); range.setValues(toWrite); if((sheet.getMaxColumns() - sheet.getLastColumn()) > 0) { sheet.deleteColumns(sheet.getLastColumn()+1, sheet.getMaxColumns() - sheet.getLastColumn()); } file = DriveApp.getFileById(spreadsheet.getId()); try { file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW); } catch(e) { file.setSharing(DriveApp.Access.DOMAIN_WITH_LINK, DriveApp.Permission.VIEW); } //This gives you a link directly to the spreadsheet sheet. return (spreadsheet.getUrl() + '#gid=' + sheet.getSheetId()); } //This function builds the summary email and sends it to the people in //the NOTIFY list //This function builds the summary email and sends it to the people in //the NOTIFY list function sendSummaryEmail(summaryEmailData) { var subject = SCRIPT_NAME+' Summary Results'; var body = subject; var htmlBody = '<html><body>'+subject; htmlBody += '<br/ >Should strip query strings: '+STRIP_QUERY_STRING; htmlBody += '<br/ >Report on redirects: '+REPORT_ON_REDIRECTS; htmlBody += '<br/ >Valid response codes: '+VALID_RESPONSE_CODES; htmlBody += '<br/ ><br/ >'; htmlBody += '<table border="1" width="95%" style="border-collapse:collapse;">'; htmlBody += '<tr>'; htmlBody += '<td align="left"><b>Acct Id</b></td>'; htmlBody += '<td align="left"><b>Acct Name</b></td>'; htmlBody += '<td align="left"><b>Exited Early</b></td>'; htmlBody += '<td align="center"><b>Unique Urls Checked</b></td>'; htmlBody += '<td align="center"><b># Broken Keyword Urls</b></td>'; htmlBody += '<td align="center"><b># Broken Ad Urls</b></td>'; htmlBody += '<td align="center"><b>Full Report</b></td>'; htmlBody += '</tr>'; for(var i in summaryEmailData) { var row = summaryEmailData[i]; htmlBody += '<tr><td align="left">'+ row.accountId + '</td><td align="left">' + row.accountName + '</td><td align="left">' + row.didExitEarly + '</td><td align="center">' + row.uniqueUrlsChecked + '</td><td align="center">' + row.numBrokenKeywords + '</td><td align="center">' + row.numBrokenAds + '</td><td align="left"><a href="'+row.sheetUrl+'">' + 'Show Details' + '</a></td></tr>'; } htmlBody += '</table>'; htmlBody += '<br/ >'; htmlBody += Utilities.formatDate(new Date(),AdWordsApp.currentAccount().getTimeZone(),'MMMM dd, yyyy @ hh:mma z'); htmlBody += '. Completed. '+Object.keys(summaryEmailData).length+' Accounts checked.'; htmlBody += '</body></html>'; var options = { htmlBody : htmlBody }; for(var i in NOTIFY) { MailApp.sendEmail(NOTIFY[i], subject, body, options); } } } //This function finds a given file on Google Drive //If it does not exist, it creates a new file //if isSpreadsheet is set, it will create a new spreadsheet //otherwise, it creates a text file. function getFile(fileName,isSpreadsheet) { var maxRetries = 0; var errors = []; while(maxRetries < 3) { try { var fileIter = DriveApp.getFilesByName(fileName); if(!fileIter.hasNext()) { info('Could not find file: '+fileName+' on Google Drive. Creating new file.'); if(isSpreadsheet) { return SpreadsheetApp.create(fileName); } else { return DriveApp.createFile(fileName,''); } } else { return fileIter.next(); } } catch(e) { errors.push(e); maxRetries++; Utilities.sleep(1000); } } if(maxRetries == 3) { throw errors.join('. '); } } //Some functions to help with logging var LOG_LEVELS = { 'error':1, 'warn':2, 'info':3, 'debug':4 }; function error(msg) { if(LOG_LEVELS['error'] <= LOG_LEVELS[LOG_LEVEL]) { log('ERROR',msg); } } function warn(msg) { if(LOG_LEVELS['warn'] <= LOG_LEVELS[LOG_LEVEL]) { log('WARN' ,msg); } } function info(msg) { if(LOG_LEVELS['info'] <= LOG_LEVELS[LOG_LEVEL]) { log('INFO' ,msg); } } function debug(msg) { if(LOG_LEVELS['debug'] <= LOG_LEVELS[LOG_LEVEL]) { log('DEBUG',msg); } } function log(type,msg) { Logger.log(type + ' - ' + msg); } |
Cet article comporte 0 commentaires