Web scraping Google Things To Do with Nodejs
Tags: webscraping, node, google
Published: 2023-02-16 16:43:46

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

![what](https://user-images.githubusercontent.com/64033139/218311143-2d9f9569-d5ef-46a9-8ba6-eba962e95af5.png)

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-Things-To-Do-with-NodeJS#index.js)

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

puppeteer.use(StealthPlugin());

const searchQuery = "Honolulu";

const URL = `https://www.google.com/travel/things-to-do`;

async function getPlaces(page) {
  const height = await page.evaluate(() => document.querySelector(".zQTmif").scrollHeight);
  const scrollIterationCount = 10;
  for (let i = 0; i < scrollIterationCount; i++) {
    await page.mouse.wheel({ deltaY: height / scrollIterationCount });
    await page.waitForTimeout(2000);
  }
  return await page.evaluate(() =>
    Array.from(document.querySelectorAll(".f4hh3d")).map((el) => ({
      thumbnail: el.querySelector(".kXlUEb img")?.getAttribute("src") || "No thumbnail",
      title: el.querySelector(".GwjAi .skFvHc")?.textContent.trim(),
      description: el.querySelector(".GwjAi .nFoFM")?.textContent.trim() || "No description",
      rating: parseFloat(el.querySelector(".GwjAi .KFi5wf")?.textContent.trim()) || "No rating",
      reviews:
        parseInt(
          el
            .querySelector(".GwjAi .jdzyld")
            ?.textContent.trim()
            .replace(/[\(|\)|\s]/gm, "")
        ) || "No reviews",
    }))
  );
}

async function getThingsToDoResults() {
  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("[type='text']");
  await page.click("[type='text']");
  await page.waitForTimeout(1000);
  await page.keyboard.type(searchQuery);
  await page.waitForTimeout(1000);
  await page.keyboard.press("Enter");
  await page.waitForSelector(".GtiGue button");
  await page.click(".GtiGue button");
  await page.waitForSelector(".f4hh3d");
  await page.waitForTimeout(2000);

  const options = Array.from(await page.$$(".iydyUc"));

  const places = {
    all: await getPlaces(page),
  };

  for (const option of options) {
    await option.click();
    await page.waitForSelector(".f4hh3d");
    await page.waitForTimeout(2000);
    const optionName = await option.$eval(".m1GHmf", (node) => node.textContent.trim());
    places[`${optionName}`] = await getPlaces(page);
  }

  await browser.close();

  return places;
}

getThingsToDoResults().then(console.log);
```

<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:

```bash
$ npm init -y
```

And then:

```bash
$ 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)

For now, we complete the setup Node.JS environment for our project and move to the step-by-step code explanation.

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

We need to extract data from HTML elements. 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/218325279-7cd49113-acb5-42e8-8c56-039fe90db2e7.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 search query and the search URL:

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

const searchQuery = "Honolulu";

const URL = `https://www.google.com/travel/things-to-do`;
```

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

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

In this function we'll use the next methods and properties to get the necessary information:

- [`evaluate()`](https://pptr.dev/api/puppeteer.page.evaluate);
- [`querySelector()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector);
- [`scrollHeight`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight);
- [`mouse.wheel()`](https://pptr.dev/api/puppeteer.mouse.wheel);
- [`waitForTimeout()`](https://pptr.dev/api/puppeteer.page.waitfortimeout);
- [`querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll);
- [`getAttribute()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute);
- [`textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent);
- [`Array.from()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from);
- [`parseFloat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat);
- [`parseInt()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt);
- [`replace()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace);

First, we need to scroll the page for loads all thumbnails. To do this we get the page scrollHeight, define `scrollIterationCount` (you need to greater this value if not all thumbnails are loaded), and then scroll the page in the [`for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement) loop:

```javascript
const height = await page.evaluate(() => document.querySelector(".zQTmif").scrollHeight);
const scrollIterationCount = 10;
for (let i = 0; i < scrollIterationCount; i++) {
  await page.mouse.wheel({ deltaY: height / scrollIterationCount });
  await page.waitForTimeout(2000);
}
```

Then, we get and return all places info from the page (using [`evaluate()`](https://pptr.dev/api/puppeteer.page.evaluate) method):

```javascript
return await page.evaluate(() =>
  Array.from(document.querySelectorAll(".f4hh3d")).map((el) => ({
    thumbnail: el.querySelector(".kXlUEb img")?.getAttribute("src") || "No thumbnail",
    title: el.querySelector(".GwjAi .skFvHc")?.textContent.trim(),
    description: el.querySelector(".GwjAi .nFoFM")?.textContent.trim() || "No description",
    rating: parseFloat(el.querySelector(".GwjAi .KFi5wf")?.textContent.trim()) || "No rating",
    reviews:
      parseInt(
        el
          .querySelector(".GwjAi .jdzyld")
          ?.textContent.trim()
          .replace(/[\(|\)|\s]/gm, "") // this RegEx matches "(", or ")", or any white space
      ) || "No reviews",
  }))
);
```

Next, we write a function to control the browser, and get information from each category:

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

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 the 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:

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

Then we wait until `"[type='text']"` selector is load ([`waitForSelector()`](https://pptr.dev/api/puppeteer.page.waitforselector) method), click on this input field and type `searchQuery` ([`keyboard.type()`](https://pptr.dev/api/puppeteer.keyboard.type) method), press "Enter" button ([`keyboard.press()`](https://pptr.dev/api/puppeteer.keyboard.press) method) and then click on "See all top sights" button:

```javascript
await page.waitForSelector("[type='text']");
await page.click("[type='text']");
await page.waitForTimeout(1000);
await page.keyboard.type(searchQuery);
await page.waitForTimeout(1000);
await page.keyboard.press("Enter");
await page.waitForSelector(".GtiGue button");
await page.click(".GtiGue button");
await page.waitForSelector(".f4hh3d");
await page.waitForTimeout(2000);
```

Then we define the `places` object and add places information from the page to `all` key:

```javascript
const places = {
  all: await getPlaces(page),
};
```

Next, we need to get all `categories` from the page and get all the places information from each category by clicking on each and setting to `places` object keys with the category name:

```javascript
const categories = Array.from(await page.$$(".iydyUc"));

for (const category of categories) {
  await category.click();
  await page.waitForSelector(".f4hh3d");
  await page.waitForTimeout(2000);
  const categoryName = await category.$eval(".m1GHmf", (node) => node.textContent.trim());
  places[`${categoryName}`] = await getPlaces(page);
}
```

And finally, we close the browser, and return the received data:

```javascript
await browser.close();

return places;
```

Now we can launch our parser:

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

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

```json
{
  "all": [
    {
      "thumbnail": "https://encrypted-tbn1.gstatic.com/licensed-image?q=tbn:ANd9GcSNARkYcqi7DBwaNx9w-qMSlFVL_nYNTuu0bX8zgIswYAjlyIx9oIpilLInYWdr7xWXGdy2zSTyhYnO_GjbBYhOJQ",
      "title": "Tonggs Beach",
      "description": "Surfing and beach",
      "rating": 4.4,
      "reviews": 68
    },
    {
      "thumbnail": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRMnzB_-HjKVPLtoD-QSTeLiLbxb87JCCaKmiI_179MO1zj1uRo30CQ41icaJrOEihrQQYwXFpvojMpEg",
      "title": "Kaluahole Beach",
      "description": "Beach",
      "rating": 2.5,
      "reviews": 2
    },
    ...and other places
  ],
  "History": [
    {
      "thumbnail": "https://encrypted-tbn2.gstatic.com/licensed-image?q=tbn:ANd9GcRlsOO0zJJJhXHxJdoms3a0VSDHdTSOlARXlcyBI7THZ64LnuaSAuBdlvYYxliXdo8fO666Fu3QSisgG-cWt9pt-Q",
      "title": "Pearl Harbor Aviation Museum",
      "description": "Exhibits on WWII aviation in the Pacific",
      "rating": 4.6,
      "reviews": 4
    },
    {
      "thumbnail": "https://encrypted-tbn1.gstatic.com/licensed-image?q=tbn:ANd9GcSgKRnVx6y-cH0Jq-h64UDAc50iwHHMOaARxnQN8xH2n_CBGIMSgQM0QGTs_qZWY65VS0sOtmgLEN9rI87k03MQiA",
      "title": "Bishop Museum",
      "description": "Polynesian culture & natural history",
      "rating": 4.6,
      "reviews": 3
    },
    ...and other places
  ],
  ...and other categories
}
```

If you want other functionality added to this blog post or 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>