DEV Community

Cover image for Web scraping Google Shopping Product Nearby Sellers with Nodejs
Mikhail Zub for SerpApi

Posted on

Web scraping Google Shopping Product Nearby Sellers with Nodejs

What will be scraped

what

Full code

If you don't need an explanation, have a look at the full code example in the online IDE

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

puppeteer.use(StealthPlugin());

const searchParams = {
  id: "16230039729797264158", // Parameter defines the ID of a product you want to get the results for
  hl: "en", // Parameter defines the language to use for the Google search
  gl: "us", // parameter defines the country to use for the Google search
};

const URL = `https://www.google.com/shopping/product/${searchParams.id}/offers?hl=${searchParams.hl}&gl=${searchParams.gl}`;

async function getSellersInfo(page) {
  return await page.evaluate(() => {
    return {
      productResults: {
        title: document.querySelector(".BvQan")?.textContent.trim(),
        reviews: parseInt(document.querySelector(".HiT7Id > span")?.getAttribute("aria-label").replace(",", "")),
        rating: parseFloat(document.querySelector(".UzThIf")?.getAttribute("aria-label")),
      },
      nearbySellers: Array.from(document.querySelectorAll(".sh-osd__offer-row")).map((el) => ({
        name: el.querySelector(".b5ycib")?.textContent.trim() || el.querySelector(".kjM2Bf")?.textContent.trim(),
        link: `https://www.google.com${el.querySelector(".b5ycib")?.getAttribute("href") || el.querySelector(".pCKrrc > a")?.getAttribute("href")}`,
        basePrice: el.querySelector(".g9WBQb")?.textContent.trim(),
        additionalPrice: {
          shipping: el.querySelector(".SuutWb tr:nth-child(2) td:last-child")?.textContent.trim(),
          tax: el.querySelector(".SuutWb tr:nth-child(3) td:last-child")?.textContent.trim(),
        },
        totalPrice: el.querySelector(".SuutWb tr:last-child td:last-child")?.textContent.trim(),
        condition: el.querySelector(".Yy9sbf")?.textContent.trim() || "New",
      })),
    };
  });
}

async function getNearbySellers() {
  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("#sh-oo__filters-wrapper");

  await page.click("#sh-oo__filters-wrapper > div:first-child a");
  await page.waitForTimeout(5000);

  const sellers = { productId: searchParams.id, ...(await getSellersInfo(page)) };

  await browser.close();

  return sellers;
}

getNearbySellers().then((result) => console.dir(result, { depth: null }));
Enter fullscreen mode Exit fullscreen mode

Preparation

First, we need to create a Node.js* project and add npm packages puppeteer, puppeteer-extra and 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 in headless or non-headless mode.

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

$ npm init -y
Enter fullscreen mode Exit fullscreen mode

And then:

$ npm i puppeteer puppeteer-extra puppeteer-extra-plugin-stealth
Enter fullscreen mode Exit fullscreen mode

*If you don't have Node.js installed, you can download it from nodejs.org and follow the installation documentation.

๐Ÿ“Œ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. You can check it on Chrome headless tests website. The screenshot below shows you a difference.

stealth

Process

We need to extract data from HTML elements. The process of getting the right CSS selectors is fairly easy via SelectorGadget Chrome extension 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 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

Code explanation

Declare puppeteer to control Chromium browser from puppeteer-extra library and StealthPlugin to prevent website detection that you are using web driver from puppeteer-extra-plugin-stealth library:

const puppeteer = require("puppeteer-extra");
const StealthPlugin = require("puppeteer-extra-plugin-stealth");
Enter fullscreen mode Exit fullscreen mode

Next, we "say" to puppeteer use StealthPlugin, write the necessary request parameters and search URL:

puppeteer.use(StealthPlugin());

const searchParams = {
  id: "16230039729797264158", // Parameter defines the ID of a product you want to get the results for
  hl: "en", // Parameter defines the language to use for the Google search
  gl: "us", // parameter defines the country to use for the Google search
};

const URL = 
    `https://www.google.com/shopping/product/${searchParams.id}/offers?hl=${searchParams.hl}&gl=${searchParams.gl}`;
Enter fullscreen mode Exit fullscreen mode

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

async function getSellersInfo(page) {
  ...
}
Enter fullscreen mode Exit fullscreen mode

In this function we get information from the page context (using evaluate() method) and save it in the returned object:

return await page.evaluate(() => ({
    ...
}));
Enter fullscreen mode Exit fullscreen mode

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

productResults: {
    title: document.querySelector(".BvQan")?.textContent.trim(),
    reviews: 
        parseInt(
            document.querySelector(".HiT7Id > span")
                ?.getAttribute("aria-label")
                .replace(",", "")
        ),
    rating: 
        parseFloat(document.querySelector(".UzThIf")?.getAttribute("aria-label")),
},
nearbySellers: Array.from(document.querySelectorAll(".sh-osd__offer-row")).map((el) => ({
    name: 
        el.querySelector(".b5ycib")?.textContent.trim() ||
        el.querySelector(".kjM2Bf")?.textContent.trim(),
    link: 
        `https://www.google.com${el.querySelector(".b5ycib")?.getAttribute("href") ||
         el.querySelector(".pCKrrc > a")?.getAttribute("href")}`,
    basePrice: el.querySelector(".g9WBQb")?.textContent.trim(),
    additionalPrice: {
        shipping: 
            el.querySelector(".SuutWb tr:nth-child(2) td:last-child")?.textContent.trim(),
        tax: el.querySelector(".SuutWb tr:nth-child(3) td:last-child")?.textContent.trim(),
    },
    totalPrice: el.querySelector(".SuutWb tr:last-child td:last-child")?.textContent.trim(),
    condition: el.querySelector(".Yy9sbf")?.textContent.trim() || "New",
})),
Enter fullscreen mode Exit fullscreen mode

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

async function getNearbySellers() {
  ...
}
Enter fullscreen mode Exit fullscreen mode

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 mode and array with arguments which we use to allow the launch of the browser process in the online IDE. And then we open a new page:

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

const page = await browser.newPage();
Enter fullscreen mode Exit fullscreen mode

Next, we change default (30 sec) time for waiting for selectors to 60000 ms (1 min) for slow internet connection with .setDefaultNavigationTimeout() method, go to URL with .goto() method and use .waitForSelector() method to wait until the selector is load:

await page.setDefaultNavigationTimeout(60000);
await page.goto(URL);
await page.waitForSelector("#sh-oo__filters-wrapper");
Enter fullscreen mode Exit fullscreen mode

And finally, we save sellers data from the page in the sellers constant (using spread syntax), close the browser, and return the received data:

const sellers = { 
    productId: searchParams.id,
    ...(await getSellersInfo(page)) 
};

await browser.close();

return sellers;
Enter fullscreen mode Exit fullscreen mode

Now we can launch our parser:

$ node YOUR_FILE_NAME # YOUR_FILE_NAME is the name of your .js file
Enter fullscreen mode Exit fullscreen mode

Output

{
  "productId": "16230039729797264158",
  "productResults": {
    "title": "Sony PlayStation 5 - Standard",
    "reviews": 63413,
    "rating": 4.5
  },
  "nearbySellers": [
    {
        "name":"Gamestop",
        "link":"https://www.google.com/url?q=https://www.gamestop.com/consoles-hardware/playstation-5/consoles/products/sony-playstation-5-console/225169.html%3Futm_source%3Dgoogle%26utm_medium%3Dfeeds%26utm_campaign%3Dunpaid_listings%26a%3D1&sa=U&ved=0ahUKEwiA6-mqkqT7AhXlFlkFHSmeDQ0Q2ykIJA&usg=AOvVaw3RHvMEi5wupRSbkZ3jmicw",
        "basePrice":"$499.99",
        "additionalPrice":{
        "shipping":"See website"
        },
        "totalPrice":"$499.99"
    },
      ...and other sellers
  ]
}
Enter fullscreen mode Exit fullscreen mode

Using Google Product Local Sellers API from SerpApi

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:

npm i google-search-results-nodejs
Enter fullscreen mode Exit fullscreen mode

Here's the full code example, if you don't need an explanation:

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: "16230039729797264158", // 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
  filter: "flocal:1", // parameter for fetching nearby sellers
};

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

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

getResults().then((result) => console.dir(result, { depth: null }));
Enter fullscreen mode Exit fullscreen mode

Code explanation

First, we need to declare SerpApi from google-search-results-nodejs library and define new search instance with your API key from SerpApi:

const SerpApi = require("google-search-results-nodejs");
const search = new SerpApi.GoogleSearch(API_KEY);
Enter fullscreen mode Exit fullscreen mode

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

const params = {
  product_id: "16230039729797264158", // 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
  filter: "flocal:1", // parameter for fetching nearby sellers
};
Enter fullscreen mode Exit fullscreen mode

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

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

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

const getResults = async () => {
  ...
};
Enter fullscreen mode Exit fullscreen mode

In this function we get json with results, and return object with data from received json using spread syntax:

const json = await getJson();
return { 
    ...json.product_results,
     nearbySellers: json.sellers_results?.online_sellers
};
Enter fullscreen mode Exit fullscreen mode

After, we run the getResults function and print all the received information in the console with the console.dir method, which allows you to use an object with the necessary parameters to change default output options:

getResults().then((result) => console.dir(result, { depth: null }));
Enter fullscreen mode Exit fullscreen mode

Output

{
   "product_id":16230039729797263000,
   "title":"Sony PlayStation 5 - Standard",
   "reviews":63413,
   "rating":4.5,
   "nearbySellers":[
      {
         "position":1,
         "name":"Gamestop",
         "link":"https://www.google.com/url?q=https://www.gamestop.com/consoles-hardware/playstation-5/consoles/products/sony-playstation-5-console/225169.html%3Futm_source%3Dgoogle%26utm_medium%3Dfeeds%26utm_campaign%3Dunpaid_listings%26a%3D1&sa=U&ved=0ahUKEwiA6-mqkqT7AhXlFlkFHSmeDQ0Q2ykIJA&usg=AOvVaw3RHvMEi5wupRSbkZ3jmicw",
         "base_price":"$499.99",
         "additional_price":{
            "shipping":"See website"
         },
         "total_price":"$499.99"
      },
    ...and other sellers
   ]
}
Enter fullscreen mode Exit fullscreen mode

If you want to see some projects made with SerpApi, write me a message.


Join us on Twitter | YouTube

Add a Feature Request๐Ÿ’ซ or a Bug๐Ÿž

Top comments (0)