Pages

sâmbătă, 29 martie 2025

News : Google Apps Script - add movies from website.

This source code with GAScript add few movies from cinemagia website:
This is the source code:
function scrapeProcessAndCleanUp() {
  const url = "https://www.cinemagia.ro/program-tv/filme-la-tv/filme-pro-tv,antena-1,tvr-1,prima-tv,diva,pro-cinema,film-cafe/azi/";
 
  let html;
  try {
    const response = UrlFetchApp.fetch(url);
    html = response.getContentText();
    Logger.log("Fetched HTML content length: ", html.length);
  } catch (error) {
    Logger.log("Error fetching HTML content: ", error.message);
    return;
  }

  let doc;
  try {
    doc = DocumentApp.create("Temporary HTML Content");
    doc.appendParagraph(html);
    doc.saveAndClose();
    Logger.log("Document created successfully with ID: ", doc.getId());
  } catch (error) {
    Logger.log("Error creating/saving document: ", error.message);
    return;
  }

  let text;
  try {
    const document = DocumentApp.openById(doc.getId());
    text = document.getBody().getText();
    Logger.log("Document text content length: ", text.length);
  } catch (error) {
    Logger.log("Error opening document or extracting text: ", error.message);
    return;
  }

  const titles = [...text.matchAll(/<li class="first">(.*?)<\/li>/g)];
  const images = [...text.matchAll(/<img src="(https:\/\/static\.cinemagia\.ro\/img\/resize\/db\/movie.*?)"/g)];
  const channels = [...text.matchAll(/<span class="r1">(.*?)<\/span>/g)];
  const times = [...text.matchAll(/<span class="r2">(.*?)<\/span>/g)];
  Logger.log("Titles found: ", titles.length);
  Logger.log("Images found: ", images.length);
  Logger.log("Channels found: ", channels.length);
  Logger.log("Times found: ", times.length);

  const extractedData = titles.map((title, index) => {
    const image = images[index] ? images[index][1] : "N/A";
    const channel = channels[index] ? channels[index][1].trim() : "N/A";
    const time = times[index] ? times[index][1].trim() : "N/A";
    return {
      title: title[1].trim(),
      image: image,
      channel: channel,
      time: time
    };
  });
  try {
    const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    const currentDate = new Date();
    extractedData.forEach((movie, rowIndex) => {
      if (movie.title !== "N/A" && movie.image !== "N/A") {
        const imageFormula = `=IMAGE("${movie.image}")`;
        const rowIndexAdjusted = sheet.getLastRow() + 1;
        sheet.appendRow([currentDate, movie.title, imageFormula, movie.channel, movie.time]);
        sheet.setRowHeight(rowIndexAdjusted, 76); // Set row height to 330px
      }
    });
    Logger.log("Processed movies count: ", extractedData.length);
  } catch (error) {
    Logger.log("Error adding data to spreadsheet: ", error.message);
  }
}
This is the result: