Web scraping Google Hotels with Nodejs
Tags: webscraping, node, google
Published: 2023-03-03 22:03:12

Currently, we don't have an API that supports extracting data from Google Hotels page, however, [it's currently in the development stage](https://github.com/serpapi/public-roadmap/issues/618) which you can track at our public-roadmap.

This blog post is to show you way how you can do it yourself with provided DIY solution below while we're working on releasing our proper API.

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

![what](https://user-images.githubusercontent.com/64033139/219440696-39b849d6-b826-4d7d-8fe2-daef5ed9cf80.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-Hotels-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/hotels/${encodeURI(searchQuery)}`;

async function getHotelsInfo(page) {
  let lastHeight = await page.evaluate(`document.querySelector(".zQTmif").scrollHeight`);
  while (true) {
    await page.waitForTimeout(500);
    await page.keyboard.press("End");
    await page.waitForTimeout(500);
    await page.keyboard.press("PageUp");
    await page.waitForTimeout(5000);
    let newHeight = await page.evaluate(`document.querySelector(".zQTmif").scrollHeight`);
    if (newHeight === lastHeight) {
      break;
    }
    lastHeight = newHeight;
  }
  return await page.evaluate(() =>
    Array.from(document.querySelectorAll(".TNNk1.nzwZbc")).map((el) => {
      const adFrom = el.querySelector(".hVE5 .ogfYpf")?.textContent.trim();
      return {
        link: `https://www.google.com/${el.querySelector(".PVOOXe")?.getAttribute("href")}`,
        images: Array.from(el.querySelectorAll(".pb2I5 img"))
          .map((el) => el.getAttribute("src"))
          .filter((el) => el),
        title: el.querySelector(".BgYkof")?.textContent.trim(),
        price: el.querySelector(".xquSSe .kixHKb > span:first-child")?.textContent.trim(),
        rating: parseFloat(el.querySelector(".KFi5wf")?.textContent.trim()) || "No rating",
        reviews:
          parseInt(
            el
              .querySelector(".jdzyld")
              ?.textContent.trim()
              .replace(/[\(|\)|\s]/gm, "")
          ) || "No reviews",
        stars: parseInt(el.querySelector(".UqrZme")?.textContent.trim()),
        options: Array.from(el.querySelectorAll(".XX3dkb > .LtjZ2d ")).map((el) => el.textContent.trim()),
        adFrom,
      };
    })
  );
}

async function getHotelsResults() {
  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(".TNNk1.nzwZbc");

  const hotels = await getHotelsInfo(page);

  await browser.close();

  return hotels;
}

getHotelsResults().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/219441133-2193b280-7216-4f5f-a6ad-42f14390e824.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/hotels/${encodeURI(searchQuery)}`;
```

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

```javascript
async function getHotelsInfo(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);
- [`waitForTimeout()`](https://pptr.dev/api/puppeteer.page.waitfortimeout);
- [`keyboard.press()`](https://pptr.dev/api/puppeteer.keyboard.press);
- [`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 results. To do this we get the results container `scrollHeight` and set it to `lastHeight` variable, then scroll the page in the [`while`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while) loop by press "End" button and check if new scrollHeight isn't change we stop the loop:

```javascript
let lastHeight = await page.evaluate(`document.querySelector(".zQTmif").scrollHeight`);
while (true) {
  await page.waitForTimeout(500);
  await page.keyboard.press("End");
  await page.waitForTimeout(500);
  await page.keyboard.press("PageUp");
  await page.waitForTimeout(5000);
  let newHeight = await page.evaluate(`document.querySelector(".zQTmif").scrollHeight`);
  if (newHeight === lastHeight) {
    break;
  }
  lastHeight = newHeight;
}
```

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

```javascript
return await page.evaluate(() =>
  Array.from(document.querySelectorAll(".TNNk1.nzwZbc")).map((el) => {
    const adFrom = el.querySelector(".hVE5 .ogfYpf")?.textContent.trim();
    return {
      link: `https://www.google.com/${el.querySelector(".PVOOXe")?.getAttribute("href")}`,
      images: Array.from(el.querySelectorAll(".pb2I5 img"))
        .map((el) => el.getAttribute("src"))
        .filter((el) => el),
      title: el.querySelector(".BgYkof")?.textContent.trim(),
      price: el.querySelector(".xquSSe .kixHKb > span:first-child")?.textContent.trim(),
      rating: parseFloat(el.querySelector(".KFi5wf")?.textContent.trim()) || "No rating",
      reviews:
        parseInt(
          el
            .querySelector(".jdzyld")
            ?.textContent.trim()
            .replace(/[\(|\)|\s]/gm, "") // this RegEx matches "(", or ")", or any white space
        ) || "No reviews",
      stars: parseInt(el.querySelector(".UqrZme")?.textContent.trim()),
      options: Array.from(el.querySelectorAll(".XX3dkb > .LtjZ2d ")).map((el) => el.textContent.trim()),
      adFrom,
    };
  })
);
```

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

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

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 `".TNNk1.nzwZbc"` selector is load ([`waitForSelector()`](https://pptr.dev/api/puppeteer.page.waitforselector) method) and add hotels information from the page to `hotels` constant:

```javascript
await page.waitForSelector(".TNNk1.nzwZbc");

const hotels = await getHotelsInfo(page);
```

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

```javascript
await browser.close();

return hotels;
```

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
[
   {
      "link":"https://www.google.com//travel/hotels/Honolulu/entity/CgoIsva7guWXuqkpEAEae0FBQm5CM2xEcERidFBBWHRBV2x0TWt0UnhmQW4xVjJMWjJDVExrWWd0eG9JVWRfZXlnWWxteHBpaEh1cXptb3pDTWpqUlFkSmJpdmlHRlRLT3NJbER6QW1vMUV5c3VOOW5VR3FFb0xZTlgxLWQ2UllDVnVmNE04QWVRSQ?utm_campaign=sharing&utm_medium=link&utm_source=htls&ved=2ahUKEwjw8ur3wJr9AhVyBRwAHcDoCHoQyvcEegQIAxAr&ts=CAESABogCgIaABIaEhQKBwjnDxACGBMSBwjnDxACGBQYATICEAAqCQoFOgNVU0QaAA&rp=OAE",
      "images":[
         "https://lh5.googleusercontent.com/p/AF1QipNLY_J7UdmiBu8U1ivimm1OFZGASPJxxsdRPXlv=w592-h404-n-k-no-v1",
         "https://lh5.googleusercontent.com/p/AF1QipOkC6UOW2plYus-TxCYqhMtBMi-0HkqyUYmrMzu=w592-h404-n-k-no-v1"
      ],
      "title":"Hilton Waikiki Beach",
      "rating":4.1,
      "reviews":823,
      "stars":4,
      "options":[
         "Breakfast ($)",
         "Free Wi-Fi"
      ],
      "adFrom":"From  Hilton Waikiki Beach"
   },
   {
      "link":"https://www.google.com//travel/hotels/Honolulu/entity/CgoI866GmIeXmos7EAEafkFBQm5CM2xuTDdXWDI2cDRoWllQXzVVazI3Vkd3OWVDbnczM215U05wRmhOOGhiMHpOaGQ4TTRoQ2ZfZVEzbU5yWDZ2U2t2THRDMy1sMlc1YWhLel9GUE9TWEhpd1ZRclgxYjhZY0VFM2ZlOEwzNTlONlJiVDNnd0k2SHpsdw?utm_campaign=sharing&utm_medium=link&utm_source=htls&ved=2ahUKEwjw8ur3wJr9AhVyBRwAHcDoCHoQyvcEegQIAxBE&ts=CAESABogCgIaABIaEhQKBwjnDxACGBMSBwjnDxACGBQYATICEAAqCQoFOgNVU0QaAA&rp=OAE",
      "images":[
         "https://lh5.googleusercontent.com/p/AF1QipMVQjGzCM8CwfDJrdrmY_CCdzwa-LQeSuF2bs5O=w592-h404-n-k-no-v1",
         "https://lh5.googleusercontent.com/p/AF1QipNSGmtQ44aKHkdXo9yU1jqZgjcu9azk7gZ4An1J=w592-h404-n-k-no-v1"
      ],
      "title":"Coconut Waikiki Hotel",
      "rating":4.2,
      "reviews":802,
      "stars":3,
      "options":[
         "Free Wi-Fi",
         "Parking ($)"
      ],
      "adFrom":"From  Booking.com"
   },
  ... and other hotels
]
```

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>