Web scraping Google Shopping Product Online Sellers with Nodejs
Tags: webscraping, node, serpapi
Published: 2022-11-25 17:25:35

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

![what](https://user-images.githubusercontent.com/64033139/200622128-5656f9d9-4858-4557-b7ce-47e894c18004.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-Online-Sellers-with-NodeJS-SerpApi#withCheerio.js)

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

const productId = "8757849604759505625"; // 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 getSellersInfo() {
  return axios.get(`https://www.google.com/shopping/product/${productId}/offers`, AXIOS_OPTIONS).then(function ({ data }) {
    let $ = cheerio.load(data);

    return {
      title: $(".BvQan")?.text().trim(),
      reviews: parseInt($(".HiT7Id > span")?.attr("aria-label")?.replace(",", "") || 0),
      rating: parseFloat($(".UzThIf")?.attr("aria-label")),
      onlineSellers: Array.from($(".sh-osd__offer-row")).map((el) => ({
        name: $(el).find(".b5ycib")?.text().trim() || $(el).find(".kjM2Bf")?.text().trim(),
        link: `https://www.google.com${$(el).find(".b5ycib")?.attr("href") || $(el).find(".pCKrrc > a")?.attr("href")}`,
        basePrice: $(el).find(".g9WBQb")?.text().trim(),
        additionalPrice: {
          shipping: $(el).find(".SuutWb tr:nth-child(2) td:last-child")?.text().trim(),
          tax: $(el).find(".SuutWb tr:nth-child(3) td:last-child")?.text().trim(),
        },
        totalPrice: $(el).find(".SuutWb tr:last-child td:last-child")?.text().trim(),
        condition: $(el).find(".Yy9sbf")?.text().trim() || "New",
      })),
      reletedProducts: Array.from($(".xyjbB")).map((el) => ({
        title: $(el).find(".YTkbnd")?.text().trim(),
        link: `https://www.google.com${$(el).find(".YTkbnd")?.attr("href")}`,
        price: $(el).find(".vzbr7d")?.text().trim(),
        reviews: parseInt($(el).find(".HiT7Id span")?.attr("aria-label")?.replace(",", "")) || "No reviews",
        rating: parseFloat($(el).find(".UzThIf")?.attr("aria-label")) || "No rating",
      })),
    };
  });
}

getSellersInfo().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/200622183-d8665422-f4fa-4f22-9eab-5ba65beee08d.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 = "8757849604759505625"; // 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 getSellersInfo() {
  return axios
    .get(`https://www.google.com/shopping/product/${productId}/offers`, 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(",", "") || 0),
      rating: parseFloat($(".UzThIf")?.attr("aria-label")),
      onlineSellers: Array.from($(".sh-osd__offer-row")).map((el) => ({
        name: 
          $(el).find(".b5ycib")?.text().trim() ||
          $(el).find(".kjM2Bf")?.text().trim(),
        link: 
          `https://www.google.com${$(el).find(".b5ycib")?.attr("href") ||
          $(el).find(".pCKrrc > a")?.attr("href")}`,
        basePrice: $(el).find(".g9WBQb")?.text().trim(),
        additionalPrice: {
          shipping: $(el).find(".SuutWb tr:nth-child(2) td:last-child")?.text().trim(),
          tax: $(el).find(".SuutWb tr:nth-child(3) td:last-child")?.text().trim(),
        },
        totalPrice: $(el).find(".SuutWb tr:last-child td:last-child")?.text().trim(),
        condition: $(el).find(".Yy9sbf")?.text().trim() || "New",
      })),
      reletedProducts: Array.from($(".xyjbB")).map((el) => ({
        title: $(el).find(".YTkbnd")?.text().trim(),
        link: `https://www.google.com${$(el).find(".YTkbnd")?.attr("href")}`,
        price: $(el).find(".vzbr7d")?.text().trim(),
        reviews: 
          parseInt($(el).find(".HiT7Id span")?.attr("aria-label")?.replace(",", "")) ||
          "No reviews",
        rating: parseFloat($(el).find(".UzThIf")?.attr("aria-label")) || "No rating",
      })),
```

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
{
   "title":"Apple iPhone 14 Pro Max - 128 GB - Space Black - Unlocked",
   "reviews":748,
   "rating":4.5,
   "onlineSellers":[
      {
         "name":"AppleOpens in a new window",
         "link":"https://www.google.com/url?q=https://www.apple.com/us/shop/go/product/MQ8N3%3Fcppart%3DUNLOCKED%26cid%3Daos-us-seo-pla&sa=U&ved=0ahUKEwj18pvWgp_7AhW6BjQIHasACEEQ2ykIJQ&usg=AOvVaw22XYRR7KYv5JrrFHZOKXPK",
         "basePrice":"$1,099.00",
         "additionalPrice":{
            "shipping":"$0.00",
            "tax":"$97.54"
         },
         "totalPrice":"$1,196.54",
         "condition":"New"
      },
      ... and other sellers
   ],
   "reletedProducts":[
      {
         "title":"iPhone 13 Pro Max 128GB Sierra ...",
         "link":"https://www.google.com/shopping/product/10665434407022887951?hl=en&gl=us&prds=epd:17054172175953313994,oid:17054172175953313994,pid:8842852891481692870,rsk:PC_8217023720749633348&sa=X&ved=0ahUKEwj18pvWgp_7AhW6BjQIHasACEEQrRIIbQ",
         "price":"$0.00",
         "reviews":11327,
         "rating":4.5
      },
    ... and other products
   ]
}
```

<h2 id='serp_api'>Using<a href="https://serpapi.com/online-sellers"> Google Product Online Sellers 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-Online-Sellers-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: "8757849604759505625", // 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
  offers: true, // parameter for fetching offers results
};

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

const getResults = async () => {
  const json = await getJson();
  return { 
    ...json.product_results,
    onlineSellers: json.sellers_results?.online_sellers,
    reletedProducts: json.related_products?.different_brand
  };
};

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: "8757849604759505625", // 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
  offers: true, // parameter for fetching offers 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,
  onlineSellers: json.sellers_results?.online_sellers,
  reletedProducts: json.related_products?.different_brand
};
```

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":8757849604759506000,
   "title":"Apple iPhone 14 Pro Max - 128 GB - Space Black - Unlocked",
   "reviews":748,
   "rating":4.5,
   "onlineSellers":[
      {
         "position":1,
         "name":"Apple",
         "link":"https://www.google.com/url?q=https://www.apple.com/us/shop/go/product/MQ8N3%3Fcppart%3DUNLOCKED%26cid%3Daos-us-seo-pla&sa=U&ved=0ahUKEwiMl-6jip_7AhUZLUQIHTI4DPoQ2ykIJQ&usg=AOvVaw1NkUFFfa7AWk6BcJQut1jp",
         "base_price":"$1,099.00",
         "additional_price":{
            "shipping":"$0.00",
            "tax":"$85.17"
         },
         "total_price":"$1,184.17"
      },
    ... and other sellers
   ],
   "reletedProducts":[
      {
         "title":"iPhone 13 Pro Max 128GB Sierra ...",
         "link":"https://www.google.com/shopping/product/10665434407022887951?hl=en&gl=us&ie=UTF-8&prds=epd:17054172175953313994,oid:17054172175953313994,pid:8842852891481692870,rsk:PC_8217023720749633348&sa=X&ved=0ahUKEwiMl-6jip_7AhUZLUQIHTI4DPoQrhIIaA",
         "price":"$0.00"
      },
      ... and other products
   ]
}
```

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

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

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>