title: Extracting img urls from webpage using Google Apps Script
body: <p>This is an Apps Script that goes through a webpage and collects img urls that are inside some div of a special class.</p>
  
  <pre><code>function getIMGs(url){
  
  var url = 'url'
  
  var  result = UrlFetchApp.fetch(url);
  
  if (result.getResponseCode() == 200) {
    var doc = Xml.parse(result, true);        
    var bodyHtml = doc.html.body.toXmlString();
    var doc = XmlService.parse(bodyHtml);
    var html = doc.getRootElement();
    var thumbs = getElementsByClassName(html, 'thumb');
    var sheet = SpreadsheetApp.getActiveSheet();
  
    for (i in Thumbs) {
      var output = '';
      var linksInMenu = getElementsByTagName(thumbs[i], 'img');
  
      for(i in linksInMenu) {
        output += XmlService.getRawFormat().format(linksInMenu[i]);
      }
  
      var linkRegExp = /data-src="(.*?)"/;
      var dataSrc = linkRegExp.exec(output);
      sheet.appendRow([dataSrc[1]]);
      }
  }
  </code></pre>
  
  <p>So first the code gets the html, and uses an auxiliary function to get certain elements, which look like this:</p>
  
  <pre><code>&lt;div class="thumb"&gt;&lt;div class="loader"&gt;&lt;span class="icon-uniE611"&gt;&lt;/span&gt;&lt;/div&gt;&lt;img src="//xxx" data-src="https://xxx/8491a83b1cacc2401907997b5b93e433c03c91f.JPG" data-target="#image-slider" data-slide-to="0"&gt;&lt;/div&gt;
  </code></pre>
  
  <p>Then the code gets the img elements, and finally extracts the data-src address via RegExp.</p>
  
  <p>While this <strong>kinda works</strong>, I have a problem:</p>
  
  <p>1) After 9 loops it crashes, <strong>on the appendRow line</strong>, as the last 4 Thumbs elements don't have data-src, hence what i'm trying to write into the spreadsheet is null.</p>
  
  <p>Any solution for this? I have fixed it for the moment by just doing 9 iterations only of the For loop, but this is far from optimal, as it's not automated and required me to go through the page to count the elements with data-src.</p>
  
  <p>Also, any suggestion of a more elegant solution will be appreciated! I will be really grateful for any helping hand!</p>
  
  <p>Cheers</p>