Web scraping with Google Apps Script (From JavaScript variable)

I’m trying to pull data from the following web page using Google Apps Script: url = view-source:https://www.vitalcountry.cz/erythritol-mouckovy/

We already use Cheerio library for some tags. Now I´m trying to scrape data from JavaScript variable. I try a lot of ways but I´m stuck. I want to get ID from datalayer. Here is datalayer :

datalayer.

I’m trying to get it via string match. Because it doesn’t work with javaScript variable. (I think)

My last 3 codes.

codes.

Answer

I managed to scrape the id of the product by getting the first script tag using a regular expresion and then breaking the content using “split()” method. The code below should return “3957”, as this is the id of the product from here https://www.vitalcountry.cz/erythritol-mouckovy/ at the moment of running the code.

const axios = require("axios");
const fetchTitles = async () => {
    try {
        const response = await axios.get('https://www.vitalcountry.cz/erythritol-mouckovy/');
        const html = response.data;
        const re = /<scriptb[^>]*>[sS]*?</scriptb[^>]*>/g
        const result = html.match(re)[0].trim();
        const result_part = result.split('"id": ')[1]
        const result_part2 = result_part.split(',')[0]
        return result_part2
    } catch (error) {
        throw error;
    }
};
fetchTitles().then((result) => console.log(result));

Let me know if I missunderstood what you wanted to do!