Web scraping Google Play Children (Kids) with Nodejs
Tags: webscraping, node, serpapi
Published: 2022-10-24 07:35:29

<h2 id='what'>What will be scraped</h2>

![what](https://user-images.githubusercontent.com/64033139/194020132-ba7e1460-765c-422c-85a6-973e03ff5be1.png)

<h2 id='full_code'>Full code</h2>

If you don't need an explanation, have a look at [the full code example in the online IDE](https://replit.com/@MikhailZub/Scrape-Google-Play-Children-Kids-with-NodeJS-SerpApi#withPuppeteer.js)

```javascript
const puppeteer = require("puppeteer-extra");
const StealthPlugin = require("puppeteer-extra-plugin-stealth");

puppeteer.use(StealthPlugin());

const searchParams = {
  hl: "en", // Parameter defines the language to use for the Google search
  gl: "us", // parameter defines the country to use for the Google search
  device: "phone", // parameter defines the search device. Options: phone, tablet, tv, chromebook
  age: null, // parameter defines age subcategory. Options: null (0-12 years), AGE_RANGE1 (0-5 years), AGE_RANGE2 (6-8 years), AGE_RANGE3 (9-12 years)
};

const URL = searchParams.age
  ? `https://play.google.com/store/apps/category/FAMILY?age=${searchParams.age}&hl=${searchParams.hl}&gl=${searchParams.gl}&device=${searchParams.device}`
  : `https://play.google.com/store/apps/category/FAMILY?hl=${searchParams.hl}&gl=${searchParams.gl}&device=${searchParams.device}`;

async function scrollPage(page, scrollContainer) {
  let lastHeight = await page.evaluate(`document.querySelector("${scrollContainer}").scrollHeight`);
  while (true) {
    await page.evaluate(`window.scrollTo(0, document.querySelector("${scrollContainer}").scrollHeight)`);
    await page.waitForTimeout(4000);
    let newHeight = await page.evaluate(`document.querySelector("${scrollContainer}").scrollHeight`);
    if (newHeight === lastHeight) {
      break;
    }
    lastHeight = newHeight;
  }
}

async function getKidsAppsFromPage(page) {
  const apps = await page.evaluate(() => {
    const mainPageInfo = Array.from(document.querySelectorAll("section .oVnAB")).reduce((result, block) => {
      const categoryTitle = block.textContent.trim();
      const apps = Array.from(block.parentElement.querySelectorAll(".ULeU3b")).map((app) => {
        const link = `https://play.google.com${app.querySelector(".Si6A0c")?.getAttribute("href")}`;
        const appId = link.slice(link.indexOf("?id=") + 4);
        if (app.querySelector(".sT93pb.DdYX5.OnEJge")) {
          return {
            title: app.querySelector(".sT93pb.DdYX5.OnEJge")?.textContent.trim(),
            appCategory: app.querySelector(".sT93pb.w2kbF:not(.ePXqnb)")?.textContent.trim(),
            link,
            rating: parseFloat(app.querySelector(".ubGTjb:last-child > div")?.getAttribute("aria-label")?.slice(6, 9)) || "No rating",
            iconThumbnail: app.querySelector(".j2FCNc img")?.getAttribute("srcset").slice(0, -3),
            appThumbnail: app.querySelector(".Vc0mnc img")?.getAttribute("src") || app.querySelector(".Shbxxd img")?.getAttribute("src"),
            video: app.querySelector(".aCy7Gf button")?.getAttribute("data-video-url") || "No video preview",
            appId,
          };
        } else {
          return {
            title: app.querySelector(".Epkrse")?.textContent.trim(),
            link,
            rating: parseFloat(app.querySelector(".vlGucd > div:first-child")?.getAttribute("aria-label")?.slice(6, 9)) || "No rating",
            thumbnail: app.querySelector(".TjRVLb img")?.getAttribute("srcset"),
            appId,
          };
        }
      });
      return {
        ...result,
        [categoryTitle]: apps,
      };
    }, {});

    return mainPageInfo;
  });
  return apps;
}

async function getMainPageInfo() {
  const browser = await puppeteer.launch({
    headless: true, // if you want to see what the browser is doing, you need to change this option to "false"
    args: ["--no-sandbox", "--disable-setuid-sandbox"],
  });

  const page = await browser.newPage();

  await page.setDefaultNavigationTimeout(60000);
  await page.goto(URL);

  await page.waitForSelector(".oVnAB");

  await scrollPage(page, ".T4LgNb");

  const apps = await getKidsAppsFromPage(page);

  await browser.close();

  return apps;
}

getMainPageInfo().then((result) => console.dir(result, { depth: null }));
```

<h2 id='preparation'>Preparation</h2>

First, we need to create a Node.js\* project and add [`npm`](https://www.npmjs.com/) packages [`puppeteer`](https://www.npmjs.com/package/puppeteer), [`puppeteer-extra`](https://www.npmjs.com/package/puppeteer-extra) and [`puppeteer-extra-plugin-stealth`](https://www.npmjs.com/package/puppeteer-extra-plugin-stealth) to control Chromium (or Chrome, or Firefox, but now we work only with Chromium which is used by default) over the [DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/) in [headless](https://developers.google.com/web/updates/2017/04/headless-chrome) or non-headless mode.

To do this, in the directory with our project, open the command line and enter `npm init -y`, and then `npm i puppeteer puppeteer-extra puppeteer-extra-plugin-stealth`.

\*<span style="font-size: 15px;">If you don't have Node.js installed, you can [download it from nodejs.org](https://nodejs.org/en/) and follow the installation [documentation](https://nodejs.dev/learn/introduction-to-nodejs).</span>

📌Note: also, you can use `puppeteer` without any extensions, but I strongly recommended use it with `puppeteer-extra` with `puppeteer-extra-plugin-stealth` to prevent website detection that you are using headless Chromium or that you are using [web driver](https://www.w3.org/TR/webdriver/). You can check it on [Chrome headless tests website](https://intoli.com/blog/not-possible-to-block-chrome-headless/chrome-headless-test.html). The screenshot below shows you a difference.

![stealth](https://user-images.githubusercontent.com/64033139/173014238-eb8450d7-616c-42ae-8b2f-24eeb5fd5916.png)

<h2 id='process'>Process</h2>

First of all, we need to scroll through all apps listings until there are no more listings loading which is the difficult part described below.

The next step is to extract data from HTML elements after scrolling is finished. The process of getting the right CSS selectors is fairly easy via [SelectorGadget Chrome extension](https://selectorgadget.com/) which able us to grab CSS selectors by clicking on the desired element in the browser. However, it is not always working perfectly, especially when the website is heavily used by JavaScript.

We have a dedicated [Web Scraping with CSS Selectors](https://serpapi.com/blog/web-scraping-with-css-selectors-using-python/#css_gadget) blog post at SerpApi if you want to know a little bit more about them.

The Gif below illustrates the approach of selecting different parts of the results using SelectorGadget.

![how](https://user-images.githubusercontent.com/64033139/194020693-a4938a1a-2928-4fe8-b5ca-33f7d31b0ec0.gif)

<h3 id='code_explanation'>Code explanation</h3>

Declare [`puppeteer`](https://www.npmjs.com/package/puppeteer-extra) to control Chromium browser from `puppeteer-extra` library and [`StealthPlugin`](https://www.npmjs.com/package/puppeteer-extra-plugin-stealth) to prevent website detection that you are using [web driver](https://www.w3.org/TR/webdriver/) from `puppeteer-extra-plugin-stealth` library:

```javascript
const puppeteer = require("puppeteer-extra");
const StealthPlugin = require("puppeteer-extra-plugin-stealth");
```

Next, we "say" to `puppeteer` use `StealthPlugin`, write the necessary request parameters and search URL using [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) (the URL may differ depending on whether the age is specified ):

```javascript
puppeteer.use(StealthPlugin());

const searchParams = {
  hl: "en", // Parameter defines the language to use for the Google search
  gl: "us", // parameter defines the country to use for the Google search
  device: "phone", // parameter defines the search device. Options: phone, tablet, tv, chromebook
  age: null, // parameter defines age subcategory. Options: null (0-12 years), AGE_RANGE1 (0-5 years), AGE_RANGE2 (6-8 years), AGE_RANGE3 (9-12 years)
};

const URL = searchParams.age
  ? `https://play.google.com/store/apps/category/FAMILY?age=${searchParams.age}&hl=${searchParams.hl}&gl=${searchParams.gl}&device=${searchParams.device}`
  : `https://play.google.com/store/apps/category/FAMILY?hl=${searchParams.hl}&gl=${searchParams.gl}&device=${searchParams.device}`;
```

If the `age` parameter is set to `null`, that means we use the default age subcategory (0-12 years) and the URL will look like this:

```javascript
"https://play.google.com/store/apps/category/FAMILY?hl=en&gl=US";
```

Otherwise, the URL will look like this:

```javascript
"https://play.google.com/store/apps/category/FAMILY?age=AGE_RANGE1&hl=en&gl=US";
```

The GIF below illustrates how the URL changes:

![urlChange](https://user-images.githubusercontent.com/64033139/196716537-75f80203-ef39-4f8c-860a-2356152ddccb.gif)

Next, we write a function to scroll the page to load all the articles:

```javascript
async function scrollPage(page, scrollContainer) {
  ...
}
```

In this function, first, we need to get `scrollContainer` height (using [`evaluate()`](https://pptr.dev/api/puppeteer.page.evaluate) method). Then we use `while` loop in which we scroll down `scrollContainer`, wait 2 seconds (using [`waitForTimeout`](https://pptr.dev/api/puppeteer.page.waitfortimeout) method), and get a new `scrollContainer` height.

Next, we check if `newHeight` is equal to `lastHeight` we stop the loop. Otherwise, we define `newHeight` value to `lastHeight` variable and repeat again until the page was not scrolled down to the end:

```javascript
let lastHeight = await page.evaluate(`document.querySelector("${scrollContainer}").scrollHeight`);
while (true) {
  await page.evaluate(`window.scrollTo(0, document.querySelector("${scrollContainer}").scrollHeight)`);
  await page.waitForTimeout(4000);
  let newHeight = await page.evaluate(`document.querySelector("${scrollContainer}").scrollHeight`);
  if (newHeight === lastHeight) {
    break;
  }
  lastHeight = newHeight;
}
```

Next, we write a function to get books data from the page:

```javascript
async function getKidsAppsFromPage(page) {
  ...
}
```

In this function, we get information from the page context and save it in the returned object. Next, we need to get all HTML elements with `"section .oVnAB"` selector ([`querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) method).

Then we use [`reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) method (it's allow to make the object with results) to iterate an array that built with [`Array.from()`]() method:

```javascript
const apps = await page.evaluate(() => {
  const mainPageInfo = Array.from(document.querySelectorAll("section .oVnAB")).reduce((result, block) => {
      ...
    }, {});

    return mainPageInfo;
});
return apps;
```

And finally, we need to get all the data using the following methods:

- [`slice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice);
- [`indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf);
- [`querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll);
- [`querySelector()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector);
- [`getAttribute()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute);
- [`textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent);
- [`trim()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim).

On each itaration step we return previous step result (using [`spread syntax`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)) and add the new category with name from `categoryTitle` constant:

We need to use two different result templates because there are two different app layouts on the page:

![image](https://user-images.githubusercontent.com/64033139/194755186-2fd3c8a1-891c-4b05-a1ff-6c16d55cc33f.png)

```javascript
const categoryTitle = block.textContent.trim();
const apps = Array.from(block.parentElement.querySelectorAll(".ULeU3b")).map((app) => {
  const link = `https://play.google.com${app.querySelector(".Si6A0c")?.getAttribute("href")}`;
  const appId = link.slice(link.indexOf("?id=") + 4);
  // if one layout appears
  if (app.querySelector(".sT93pb.DdYX5.OnEJge")) {
    return {
      title: app.querySelector(".sT93pb.DdYX5.OnEJge")?.textContent.trim(),
      appCategory: app.querySelector(".sT93pb.w2kbF:not(.ePXqnb)")?.textContent.trim(),
      link,
      rating: parseFloat(app.querySelector(".ubGTjb:last-child > div")?.getAttribute("aria-label")?.slice(6, 9)) || "No rating",
      iconThumbnail: app.querySelector(".j2FCNc img")?.getAttribute("srcset").slice(0, -3),
      appThumbnail: app.querySelector(".Vc0mnc img")?.getAttribute("src") || app.querySelector(".Shbxxd img")?.getAttribute("src"),
      video: app.querySelector(".aCy7Gf button")?.getAttribute("data-video-url") || "No video preview",
      appId,
    };
  // else extracting second layout
  } else {
    return {
      title: app.querySelector(".Epkrse")?.textContent.trim(),
      link,
      rating: parseFloat(app.querySelector(".vlGucd > div:first-child")?.getAttribute("aria-label")?.slice(6, 9)) || "No rating",
      thumbnail: app.querySelector(".TjRVLb img")?.getAttribute("srcset"),
      appId,
    };
  }
});
return {
  ...result,
  [categoryTitle]: apps,
```

Next, write a function to control the browser, and get information:

```javascript
async function getMainPageInfo() {
  ...
}
```

In this function first we need to define `browser` using `puppeteer.launch({options})` method with current `options`, such as `headless: true` and `args: ["--no-sandbox", "--disable-setuid-sandbox"]`.

These options mean that we use [headless](https://developers.google.com/web/updates/2017/04/headless-chrome) mode and array with [arguments](https://peter.sh/experiments/chromium-command-line-switches/) which we use to allow the launch of the browser process in the online IDE. And then we open a new `page`:

```javascript
const browser = await puppeteer.launch({
  headless: true, // if you want to see what the browser is doing, you need to change this option to "false"
  args: ["--no-sandbox", "--disable-setuid-sandbox"],
});

const page = await browser.newPage();
```

Next, we change default ([30 sec](https://github.com/puppeteer/puppeteer/blob/2a0eefb99f0ae00dacc9e768a253308c0d18a4c3/src/common/TimeoutSettings.ts#L17)) time for waiting for selectors to 60000 ms (1 min) for slow internet connection with [`.setDefaultNavigationTimeout()`](https://pptr.dev/api/puppeteer.page.setdefaultnavigationtimeout) method, go to `URL` with [`.goto()`](https://pptr.dev/api/puppeteer.page.goto) method and use [`.waitForSelector()`](https://pptr.dev/api/puppeteer.page.waitforselector) method to wait until the selector is load:

```javascript
await page.setDefaultNavigationTimeout(60000);
await page.goto(URL);
await page.waitForSelector(".oVnAB");
```

And finally, we wait until the page was scrolled, save apps data from the page in the `apps` constant, close the browser, and return the received data:

```javascript
await scrollPage(page, ".T4LgNb");

const apps = await getKidsAppsFromPage(page);

await browser.close();

return apps;
```

Now we can launch our parser:

```bash
$ node YOUR_FILE_NAME # YOUR_FILE_NAME is the name of your .js file
```

<h2 id='output'>Output</h2>

```json
{
   "New & updated":[
      {
         "title":"PBS KIDS Video",
         "appCategory":"Education",
         "link":"https://play.google.com/store/apps/details?id=org.pbskids.video",
         "rating":4.4,
         "iconThumbnail":"https://play-lh.googleusercontent.com/Fel1apzw2D5Qy1xZ9HYQ3LPEJqZB5OxdhkorYLrQ7fTUIdGU8uIY_qiN9ZvaRs9eItQ=s128-rw",
         "appThumbnail":"https://play-lh.googleusercontent.com/9MSE2M5sGVy73d75bBemSfZQicBp1cOkjjG-c3tvW5vOVrpOaXdAyjmnbVcBCMWSaLk=w416-h235-rw",
         "video":"No video preview",
         "appId":"org.pbskids.video"
      },
      ... and other results
   ],
   "Encourage kindness":[
      {
         "title":"Breathe, Think, Do with Sesame",
         "link":"https://play.google.com/store/apps/details?id=air.com.sesameworkshop.ResilienceThinkBreathDo",
         "rating":4,
         "thumbnail":"https://play-lh.googleusercontent.com/-UbCkW4xbM661t4mndTi7owhXY0GYBCRQn4Pxl7_1tXgCCvqKsJwUKE-O61NO0CuJA=s512-rw 2x",
         "appId":"air.com.sesameworkshop.ResilienceThinkBreathDo"
      },
      ... and other results
   ],
   ... and other categories
}
```

<h2 id='serp_api'>Using<a href="https://serpapi.com/google-play-apps"> Google Play Apps Store API </a>from SerpApi</h2>

This section is to show the comparison between the DIY solution and our solution.

The biggest difference is that you don't need to create the parser from scratch and maintain it.

There's also a chance that the request might be blocked at some point from Google, we handle it on our backend so there's no need to figure out how to do it yourself or figure out which CAPTCHA, proxy provider to use.

First, we need to install [`google-search-results-nodejs`](https://www.npmjs.com/package/google-search-results-nodejs):

```bash
npm i google-search-results-nodejs
```

Here's the [full code example](https://replit.com/@MikhailZub/Scrape-Google-Play-Children-Kids-with-NodeJS-SerpApi#withSerpApi.js), if you don't need an explanation:

```javascript
const SerpApi = require("google-search-results-nodejs");
const search = new SerpApi.GoogleSearch(process.env.API_KEY); //your API key from serpapi.com

const params = {
  engine: "google_play", // search engine
  gl: "us", // parameter defines the country to use for the Google search
  hl: "en", // parameter defines the language to use for the Google search
  store: "apps", // parameter defines the type of Google Play store
  store_device: "phone", // parameter defines the search device. Options: phone, tablet, tv, chromebook, watch, car
  apps_category: "FAMILY", // parameter defines the apps and games store category. In this case we use "FAMILY" to scrape Google Play Children apps
};

const getJson = () => {
  return new Promise((resolve) => {
    search.json(params, resolve);
  });
};

const getResults = async () => {
  const json = await getJson();
  const appsResults = json.organic_results.reduce((result, category) => {
    const { title: categoryTitle, items } = category;
    const apps = items.map((app) => {
      const { title, link, rating, category, video = "No video preview", thumbnail, product_id } = app;
      if (category) {
        return {
          title,
          link,
          rating,
          category,
          video,
          thumbnail,
          appId: product_id,
        };
      } else {
        return {
          title,
          link,
          rating,
          thumbnail,
          appId: product_id,
        };
      }
    });
    return {
      ...result,
      [categoryTitle]: apps,
    };
  }, {});
  return appsResults;
};

getResults().then((result) => console.dir(result, { depth: null }));
```

<h3 id='serp_api_code_explanation'>Code explanation</h3>

First, we need to declare `SerpApi` from [`google-search-results-nodejs`](https://www.npmjs.com/package/google-search-results-nodejs) library and define new `search` instance with your API key from [SerpApi](https://serpapi.com/manage-api-key):

```javascript
const SerpApi = require("google-search-results-nodejs");
const search = new SerpApi.GoogleSearch(API_KEY);
```

Next, we write the necessary parameters for making a request:

```javascript
const params = {
  engine: "google_play", // search engine
  gl: "us", // parameter defines the country to use for the Google search
  hl: "en", // parameter defines the language to use for the Google search
  store: "apps", // parameter defines the type of Google Play store
  store_device: "phone", // parameter defines the search device. Options: phone, tablet, tv, chromebook, watch, car
  apps_category: "FAMILY", // parameter defines the apps and games store category. In this case we use "FAMILY" to scrape Google Play Children apps
};
```

Next, we wrap the search method from the SerpApi library in a promise to further work with the search results:

```javascript
const getJson = () => {
  return new Promise((resolve) => {
    search.json(params, resolve);
  });
};
```

And finally, we declare the function `getResult` that gets data from the page and return it:

```javascript
const getResults = async () => {
  ...
};
```

In this function first, we get `json` with results, then we need to iterate `organic_results` array in the received `json`. To do this we use [`reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) method (it's allow to make the object with results). On each itaration step we return previous step result (using [`spread syntax`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)) and add the new category with name from `categoryTitle` constant:

```javascript
  const json = await getJson();
  const appsResults = json.organic_results.reduce((result, category) => {
    ...
    return {
      ...result,
      [categoryTitle]: apps,
    };
  }, {});
  return appsResults;
```

Next, we destructure `category` element, redefine `title` to `categoryTitle` constant, and itarate the `items` array to get all books from this category. To do this we need to destructure the `book` element, set default value "No rating" for `rating` and return this constants:

We need to use two different result templates because there are two different app layouts on the page:

![image](https://user-images.githubusercontent.com/64033139/194755186-2fd3c8a1-891c-4b05-a1ff-6c16d55cc33f.png)

```javascript
const apps = items.map((app) => {
  const { title, link, rating, category, video = "No video preview", thumbnail, product_id } = app;
  // if one layout appears
  if (category) {
    return {
      title,
      link,
      rating,
      category,
      video,
      thumbnail,
      appId: product_id,
    };
    // else extracting second layout
  } else {
    return {
      title,
      link,
      rating,
      thumbnail,
      appId: product_id,
    };
  }
});
```

After, we run the `getResults` function and print all the received information in the console with the [`console.dir`](https://nodejs.org/api/console.html#consoledirobj-options) method, which allows you to use an object with the necessary parameters to change default output options:

```javascript
getResults().then((result) => console.dir(result, { depth: null }));
```

<h2 id='serp_api_output'>Output</h2>

```json
{
   "New & updated":[
      {
         "title":"PBS KIDS Video",
         "link":"https://play.google.com/store/apps/details?id=org.pbskids.video",
         "rating":4.4,
         "category":"Education",
         "video":"No video preview",
         "thumbnail":"https://play-lh.googleusercontent.com/Fel1apzw2D5Qy1xZ9HYQ3LPEJqZB5OxdhkorYLrQ7fTUIdGU8uIY_qiN9ZvaRs9eItQ=s64-rw",
         "appId":"org.pbskids.video"
      },
      ... and other results
   ],
   "Enriching games":[
      {
         "title":"Violet - My Little Pet",
         "link":"https://play.google.com/store/apps/details?id=ro.Funbrite.VioletMyLittlePet",
         "rating":4.7,
         "thumbnail":"https://play-lh.googleusercontent.com/lnv-uzrGlkY3Ke_UofPyq77k4RDjatyIOrCnTGoBSWtIF6sluX-eys3MH8Z43kZZ6g=s256-rw",
         "appId":"ro.Funbrite.VioletMyLittlePet"
      },
      ... and other results
   ],
   ... and other categories
}
```

<h2 id='links'>Links</h2>

- [Code in the online IDE](https://replit.com/@MikhailZub/Scrape-Google-Play-Children-Kids-with-NodeJS-SerpApi#index.js)
- [Google Play Apps Store API](https://serpapi.com/google-play-apps)

If you want to see some projects made with SerpApi, [write me a message](mailto:miha01012019@gmail.com).

---

<p style="text-align: center;">Join us on <a href="https://twitter.com/serp_api">Twitter</a> | <a href="https://www.youtube.com/channel/UCUgIHlYBOD3yA3yDIRhg_mg">YouTube</a></p>
<p style="text-align: center;">Add a  <a href="https://github.com/serpapi/public-roadmap/issues">Feature Request</a>💫 or a <a href="https://github.com/serpapi/public-roadmap/issues">Bug</a>🐞</p>