Scroll to Top
💻
Free Code
Users get ready-to-use code at no cost.
📋
Easy Copy
Copy and use the code instantly.
Quick Learning
Understand concepts fast and clearly.
📝
Step-by-Step
Follow simple instructions to implement.
📅 August 16, 2024 💻 Tutorial ⭐ Beginner Friendly

Automating Data Import from Webpages to Google Sheets with Apps Script

Author Avatar

Ashish Dwivedi

Editorial Team • Tech Writer

About This Tutorial

Automating data import from webpages to Google Sheets using Google Apps Script lets you pull real-time information from any site in the world. With UrlFetchApp, extract and update live data like prices, news, or stats—directly into your sheet—saving time, reducing errors, and boosting global productivity.
  1. Step 1: Click on the Copy button to copy the code snippet.
  2. Step 2: Paste the copied code into your project’s script editor.

Apps Scripts Blog

Read Blog

📂 javascript
⚡ script1.js
⚡ script1.js
function importDataFromWeb() {
  var url = "www.example.com"; // Replace with the correct URL of the webpage
  var filterValues = [""]; // Specify the values to filter on
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

  // Fetch the webpage content
  var response = UrlFetchApp.fetch(url);
  var content = response.getContentText();

  // Regex to extract table, rows, and cells
  var tableRegex = /<table[^>]*>([\s\S]*?)<\/table>/g;
  var rowRegex = /<tr[^>]*>([\s\S]*?)<\/tr>/g;
  var cellRegex = /<t[hd][^>]*>([\s\S]*?)<\/t[hd]>/g;

  // Find all tables in the page
  var tables = content.match(tableRegex);

  if (tables) {
    tables.forEach(function(table) {
      var rows = table.match(rowRegex);

      if (rows) {
        rows.forEach(function(row) {
          var cells = row.match(cellRegex);

          if (cells) {
            // Check if all filter values exist in the row
            var matchFound = filterValues.every(function(filterValue) {
              return cells.some(function(cell) {
                return cell.includes(filterValue);
              });
            });

            if (matchFound) {
              // Specify the desired column indexes to import (starting from 0)
              var columnIndexes = [0, 1, 2, 3]; // Example: Import first 4 columns

              // Extract cell values and remove HTML tags
              var values = columnIndexes.map(function(index) {
                var cell = cells[index];
                return cell ? cell.replace(/<\/?[^\>]+>/g, '') : '';
              });

              // Append the extracted row to the sheet
              sheet.appendRow(values);
            }
          }
        });
      }
    });
  } else {
    Logger.log("No table found on the webpage.");
  }
}