Web scraping Google Shopping Product Specs with Nodejs
Tags: webscraping, node, serpapi
Published: 2022-11-28 16:47:28

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

![what](https://user-images.githubusercontent.com/64033139/200793670-6d385bc9-67fc-4ffa-b12d-840ee5ea05bc.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/Google-Shopping-Product-Specs-with-NodeJS-SerpApi#withCheerio.js)

```javascript
const cheerio = require("cheerio");
const axios = require("axios");

const productId = "14938360545167499200"; // Parameter defines the ID of a product you want to get the results for

const AXIOS_OPTIONS = {
  headers: {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36",
  }, // adding the User-Agent header as one way to prevent the request from being blocked
  params: {
    hl: "en", // parameter defines the language to use for the Google search
    gl: "us", // parameter defines the country to use for the Google search
  },
};

function getProductSpecs() {
  return axios.get(`https://www.google.com/shopping/product/${productId}/specs`, AXIOS_OPTIONS).then(function ({ data }) {
    let $ = cheerio.load(data);

    let category;
    return {
      productId,
      title: $(".BvQan")?.text().trim(),
      reviews: parseInt($(".HiT7Id > span")?.attr("aria-label")?.replace(",", "")),
      rating: parseFloat($(".UzThIf")?.attr("aria-label")),
      extensions: Array.from($(".OA4wid")).map((el) => $(el).text().replaceAll("·", "").trim()),
      description: $(".bwcLrc")?.text().trim(),
      specsResults: Array.from($(".O2pTHb tr")).reduce((results, el) => {
        if (!$(el).hasClass("vm91i")) {
          category = $(el).text().trim();
        } else {
          results[`${category}`] = {
            ...results[`${category}`],
            [$(el).find(".ipBhab")?.text().trim()]: $(el).find(".AnDf0c")?.text().trim(),
          };
        }
        return { ...results };
      }, {}),
    };
  });
}

getProductSpecs().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 [`cheerio`](https://www.npmjs.com/package/cheerio) to parse parts of the HTML markup, and [`axios`](https://www.npmjs.com/package/axios) to make a request to a website.

To do this, in the directory with our project, open the command line and enter:

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

And then:

```bash
$ npm i cheerio axios
```

\*<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>

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

First of all, 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.

![how](https://user-images.githubusercontent.com/64033139/200794159-0aaa05b6-79e7-412e-ad54-bb210c1cd637.gif)

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

Declare constants from [`cheerio`](https://www.npmjs.com/package/cheerio) and [`axios`](https://www.npmjs.com/package/axios) libraries:

```javascript
const cheerio = require("cheerio");
const axios = require("axios");
```

Next, we write product ID, the request options: [`HTTP headers`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) with [`User-Agent`](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) which is used to act as a "real" user visit, and the necessary parameters for making a request:

```javascript
const productId = "14938360545167499200"; // Parameter defines the ID of a product you want to get the results for

const AXIOS_OPTIONS = {
  headers: {
    "User-Agent": 
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36",
  }, // adding the User-Agent header as one way to prevent the request from being blocked
  params: {
    hl: "en", // parameter defines the language to use for the Google search
    gl: "us", // parameter defines the country to use for the Google search
  },
};
```

📌Note: [Default `axios` request user-agent is `axios/<axios_version>`](https://github.com/axios/axios/blob/892c241773e7dda78a969ac1faa9b365e24f6cc8/lib/adapters/http.js#L224) so websites understand that it's a script that sends a request and might block it. [Check what's your user-agent](https://www.whatismybrowser.com/detect/what-is-my-user-agent/).

Next, we write a function that makes the request and returns the received data. We received the response from [`axios`](https://www.npmjs.com/package/axios) request that has `data` key that we [destructured](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) and parse it with [`cheerio`](https://www.npmjs.com/package/cheerio):

```javascript
function getProductSpecs() {
  return axios
    .get(`https://www.google.com/shopping/product/${productId}/specs`, AXIOS_OPTIONS)
    .then(function ({ data }) {
        let $ = cheerio.load(data);
    ...
  })
}
```

Next, we need to get the different parts of the page using next methods:

- [`$()`](https://api.jquery.com/class-selector/);
- [`find()`](https://api.jquery.com/find/);
- [`text()`](https://api.jquery.com/text/);
- [`trim()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim);
- [`attr()`](https://api.jquery.com/attr/);
- [`Array.from()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from);
- [`parseInt()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt);
- [`parseFloat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat).

```javascript
  title: $(".BvQan")?.text().trim(),
  reviews: parseInt($(".HiT7Id > span")?.attr("aria-label")?.replace(",", "")),
  rating: parseFloat($(".UzThIf")?.attr("aria-label")),
  extensions: Array.from($(".OA4wid")).map((el) => $(el).text().replaceAll("·", "").trim()),
  description: $(".bwcLrc")?.text().trim(),
```

The screenshot below shows you what structure in the DOM has a specs table:

![table](https://user-images.githubusercontent.com/64033139/200808097-ac3d4657-8c3d-4638-8d25-2b43b6247e3b.png)

To get specs we need to write an empty variable to change the current category. Then we use [`reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) method (it allows to make the object with results) to iterate an array that is built with [`Array.from()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) method.

In the `reduce` function we check if the current element doesn't have class `"vm91i"` ([hasClass()](https://api.jquery.com/hasclass/) method) we set it to category. The next elements are from this category, so we add them to the current category (using [`spread syntax`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). And repeat it for the next category:

```javascript
let category;
return {
    ...
    specsResults: Array.from($(".O2pTHb tr")).reduce((results, el) => {
    if (!$(el).hasClass("vm91i")) {
        category = $(el).text().trim();
    } else {
        results[`${category}`] = {
        ...results[`${category}`],
        [$(el).find(".ipBhab")?.text().trim()]: $(el).find(".AnDf0c")?.text().trim(),
        };
    }
    return { ...results };
    }, {}),
};
```

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
{
   "productId":"14938360545167499200",
   "title":"Apple iPhone 12 Pro - 128 GB - Silver - Unlocked",
   "reviews":5109,
   "rating":4.5,
   "extensions":[
      "Smartphone",
      "Dual SIM",
      "iOS",
      "5G",
      "With Wireless Charging",
      "Triple Lens",
      "GSM",
      "CDMA",
      "With OLED Display",
      "Facial Recognition"
   ],
   "description":"Apple · iPhone · iPhone 12 · iPhone 12 Pro · iOS · 6.1′′ · Facial Recognition · 12 MP front camera · 12 MP rear camera · Smartphone · With Wireless Charging. Beautifully bright 6.1-inch Super Retina XDR display. Ceramic Shield with 4x better drop performance. Incredible low-light photography with a new Pro camera system, and 4x optical zoom range. Cinema-grade Dolby Vision video recording, editing, and playback. Night mode portraits and next-level AR experiences with the LiDAR Scanner. Powerful A14 Bionic chip. 5G capable. And new MagSafe accessories for easy attach and faster wireless charging. For infinitely spectacular possibilities. Legal. The display has rounded corners. When measured as a rectangle, the screen is 6.06 inches diagonally. Actual viewable area is less. Claim based on iPhone 12 Pro Ceramic Shield front compared with previous-generation iPhone. Data plan required. 5G is available in select markets and through select carriers. Speeds vary based on site conditions and carrier. Accessories are sold separately. Apple ProRAW coming soon. iPhone 12 Pro is splash, water, and dust resistant and was tested under controlled laboratory conditions with a rating of IP68 under IEC standard 60529 (maximum depth of 6 meters up to 30 minutes). Splash, water, and dust resistance are not permanent conditions. Resistance might decrease as a result of normal wear. Do not attempt to charge a wet iPhone; refer to the user guide for cleaning and drying instructions.",
   "specsResults":{
      "General":{
         "Product Type":"Smartphone",
         "Manufacturer Model Number":"A2341",
         "Form Factor":"Touch",
        ...and oter specs
      },
      "Cellular":{
         "Technology":"CDMA2000 1X / GSM / WCDMA (UMTS)",
         "Mobile Broadband Generation":"5G",
         "Service Provider":"Not specified",
        ...and oter specs
      },
      ...and other categories
   }
}
```

<h2 id='serp_api'>Using<a href="https://serpapi.com/specs-results"> Google Product Specs Results 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/Google-Shopping-Product-Specs-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 = {
  product_id: "14938360545167499200", // Parameter defines the ID of a product you want to get the results for.
  engine: "google_product", // search engine
  device: "desktop", //Parameter defines the device to use to get the results. It can be set to "desktop" (default), "tablet", or "mobile"
  hl: "en", // parameter defines the language to use for the Google search
  gl: "us", // parameter defines the country to use for the Google search
  specs: true, // parameter for fetching specs results
};

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

const getResults = async () => {
  const json = await getJson();
  return { ...json.product_results, specsResults: json.specs_results };
};

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 = {
  product_id: "14938360545167499200", // Parameter defines the ID of a product you want to get the results for.
  engine: "google_product", // search engine
  device: "desktop", //Parameter defines the device to use to get the results. It can be set to "desktop" (default), "tablet", or "mobile"
  hl: "en", // parameter defines the language to use for the Google search
  gl: "us", // parameter defines the country to use for the Google search
  specs: true, // parameter for fetching specs results
};
```

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 we get `json` with results, and return object with data from received `json` using [`spread syntax`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax):

```javascript
const json = await getJson();
return { ...json.product_results, specsResults: json.specs_results };
```

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
{
   "product_id":14938360545167500000,
   "title":"Apple iPhone 12 Pro - 128 GB - Silver - Unlocked",
   "reviews":5109,
   "rating":4.5,
   "extensions":[
      "Smartphone",
      "Dual SIM",
      "iOS",
      "5G",
      "With Wireless Charging",
      "Triple Lens",
      "GSM",
      "CDMA",
      "With OLED Display",
      "Facial Recognition"
   ],
   "description":"Apple · iPhone · iPhone 12 · iPhone 12 Pro · iOS · 6.1′′ · Facial Recognition · 12 MP front camera · 12 MP rear camera · Smartphone · With Wireless Charging. Beautifully bright 6.1-inch Super Retina XDR display. Ceramic Shield with 4x better drop performance. Incredible low-light photography with a new Pro camera system, and 4x optical zoom range. Cinema-grade Dolby Vision video recording, editing, and playback. Night mode portraits and next-level AR experiences with the LiDAR Scanner. Powerful A14 Bionic chip. 5G capable. And new MagSafe accessories for easy attach and faster wireless charging. For infinitely spectacular possibilities. Legal. The display has rounded corners. When measured as a rectangle, the screen is 6.06 inches diagonally. Actual viewable area is less. Claim based on iPhone 12 Pro Ceramic Shield front compared with previous-generation iPhone. Data plan required. 5G is available in select markets and through select carriers. Speeds vary based on site conditions and carrier. Accessories are sold separately. Apple ProRAW coming soon. iPhone 12 Pro is splash, water, and dust resistant and was tested under controlled laboratory conditions with a rating of IP68 under IEC standard 60529 (maximum depth of 6 meters up to 30 minutes). Splash, water, and dust resistance are not permanent conditions. Resistance might decrease as a result of normal wear. Do not attempt to charge a wet iPhone; refer to the user guide for cleaning and drying instructions.",
   "specsResults":{
      "general":{
         "product_type":"Smartphone",
         "manufacturer_model_number":"A2341",
         "form_factor":"Touch",
         ...and oter specs
      },
      "cellular":{
         "technology":"CDMA2000 1X / GSM / WCDMA (UMTS)",
         "mobile_broadband_generation":"5G",
         "service_provider":"Not specified",
         ...and oter specs
      },
      ...and other categories
   }
}
```

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

- [Code in the online IDE](https://replit.com/@MikhailZub/Google-Shopping-Product-Specs-with-NodeJS-SerpApi#index.js)
- [Google Product Specs Results API](https://serpapi.com/specs-results)

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>