Web scraping Yelp Reviews with Nodejs
Tags: webscraping, node, serpapi
Published: 2022-12-22 18:07:16

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

![what](https://user-images.githubusercontent.com/64033139/205449412-7a979361-2c4c-4249-bdf2-9e36ad244fad.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/Scrape-Yelp-Reviews-with-NodeJS-SerpApi#withPuppeteer.js)

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

puppeteer.use(StealthPlugin());

const reviewsLimit = 50; // hardcoded limit for demonstration purpose

const URL = `https://www.yelp.com/biz/kfc-seattle-18?osq=kfc#reviews`;

async function getReviewsFromPage(page) {
  return await page.evaluate(() => {
    return Array.from(document.querySelectorAll("section[aria-label='Recommended Reviews'] div > ul > li")).map((el) => {
      const thumbnails = el.querySelector("div > a > img").getAttribute("srcset")?.split(", ");
      const bestResolutionThumbnail = thumbnails && thumbnails[thumbnails.length - 1].split(" ")[0];
      return {
        user: {
          name: el.querySelector(".user-passport-info span > a")?.textContent,
          link: `https://www.yelp.com${el.querySelector(".user-passport-info span > a")?.getAttribute("href")}`,
          thumbnail: bestResolutionThumbnail,
          address: el.querySelector(".user-passport-info div > span")?.textContent,
          friends: el.querySelector("[aria-label='Friends'] span > span")?.textContent,
          photos: el.querySelector("[aria-label='Photos'] span > span")?.textContent,
          reviews: el.querySelector("[aria-label='Reviews'] span > span")?.textContent,
          eliteYear: el.querySelector(".user-passport-info div > a > span")?.textContent,
        },
        comment: {
          text: el.querySelector("span[lang]")?.textContent,
          language: el.querySelector("span[lang]")?.getAttribute("lang"),
        },
        date: el.querySelector(":scope > div > div:nth-child(2) div:nth-child(2) > span")?.textContent,
        rating: el.querySelector("span > div[role='img']").getAttribute("aria-label")?.split(" ")?.[0],
        photos: Array.from(el.querySelectorAll(":scope > div > div:nth-child(5) > div > div")).map((el) => {
          const captionString = el.querySelector("img").getAttribute("alt");
          const captionStart = captionString.indexOf(".");
          const caption = captionStart !== -1 ? captionString.slice(captionStart + 2) : undefined;
          return {
            link: el.querySelector("img").getAttribute("src"),
            caption,
          };
        }),
        feedback: {
          useful: el.querySelector(":scope > div > div:last-child span:nth-child(1) button span > span > span")?.textContent,
          funny: el.querySelector(":scope > div > div:last-child span:nth-child(2) button span > span > span")?.textContent,
          cool: el.querySelector(":scope > div > div:last-child span:nth-child(3) button span > span > span")?.textContent,
        },
      };
    });
  });
}

async function getReviews() {
  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);

  const reviews = [];

  while (true) {
    await page.waitForSelector("section[aria-label='Recommended Reviews'] div > ul");
    reviews.push(...(await getReviewsFromPage(page)));
    const isNextPage = await page.$("a[aria-label='Next']");
    if (!isNextPage || reviews.length >= reviewsLimit) break;
    await page.click("a[aria-label='Next']");
    await page.waitForTimeout(3000);
  }

  await browser.close();

  return reviews;
}

getReviews().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 [`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)

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

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/205449503-15cd0d34-6415-4020-88df-c0f3dea3d121.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`, set how many results we want to receive (`reviewsLimit` constant), and search URL:

📌Note: you can get place reviews URL from our [Web scraping Yelp Organic Results with Nodejs](https://serpapi.ghost.io/blog/web-scraping-yelp-organic-results-with-nodejs/#full_code) blog post in the DIY solution section.

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

const reviewsLimit = 50; // hardcoded limit for demonstration purpose

const URL = `https://www.yelp.com/biz/kfc-seattle-18?osq=kfc#reviews`;
```

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

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

Then, we get information from the page context (using [`evaluate()`](https://pptr.dev/api/puppeteer.page.evaluate) method) and save it in the returned object:

```javascript
return await page.evaluate(() => ({
    ...
}));
```

Next, we return a new array ([`Array.from()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) method) from all `"section[aria-label='Recommended Reviews'] div > ul > li"` selectors ([`querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) method):

```javascript
let isAds = false;
    return Array.from(document.querySelectorAll("section[aria-label='Recommended Reviews'] div > ul > li")).map((el) => {
    ...
});
```

To make returned result object we need to get `thumbnails` in all resolutions. Then we get the last resolution link - it's the best one:

```javascript
const thumbnails = el.querySelector("div > a > img").getAttribute("srcset")?.split(", ");
const bestResolutionThumbnail = thumbnails && thumbnails[thumbnails.length - 1].split(" ")[0];
```

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

- [`querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll);
- [`querySelector()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector);
- [`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);
- [`split()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split);
- [`slice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice).

```javascript
return {
  user: {
    name: el.querySelector(".user-passport-info span > a")?.textContent,
    link: `https://www.yelp.com${el.querySelector(".user-passport-info span > a")?.getAttribute("href")}`,
    thumbnail: bestResolutionThumbnail,
    address: el.querySelector(".user-passport-info div > span")?.textContent,
    friends: el.querySelector("[aria-label='Friends'] span > span")?.textContent,
    photos: el.querySelector("[aria-label='Photos'] span > span")?.textContent,
    reviews: el.querySelector("[aria-label='Reviews'] span > span")?.textContent,
    eliteYear: el.querySelector(".user-passport-info div > a > span")?.textContent,
  },
  comment: {
    text: el.querySelector("span[lang]")?.textContent,
    language: el.querySelector("span[lang]")?.getAttribute("lang"),
  },
  date: el.querySelector(":scope > div > div:nth-child(2) div:nth-child(2) > span")?.textContent,
  rating: el.querySelector("span > div[role='img']").getAttribute("aria-label")?.split(" ")?.[0],
  photos: Array.from(el.querySelectorAll(":scope > div > div:nth-child(5) > div > div")).map((el) => {
    const captionString = el.querySelector("img").getAttribute("alt");
    const captionStart = captionString.indexOf(".");
    const caption = captionStart !== -1 ? captionString.slice(captionStart + 2) : undefined;
    return {
      link: el.querySelector("img").getAttribute("src"),
      caption,
    };
  }),
  feedback: {
    useful: el.querySelector(":scope > div > div:last-child span:nth-child(1) button span > span > span")?.textContent,
    funny: el.querySelector(":scope > div > div:last-child span:nth-child(2) button span > span > span")?.textContent,
    cool: el.querySelector(":scope > div > div:last-child span:nth-child(3) button span > span > span")?.textContent,
  },
};
```

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

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

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 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 and define the `reviews` array:

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

const reviews = [];
```

Next, we use `while` loop ([`while`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while)) in which we use [`.waitForSelector()`](https://pptr.dev/api/puppeteer.page.waitforselector) method to wait until the selector is load, add results from the page to `reviews` array (using [`spread syntax`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)), check if the next page button is present on the page ([`$`](https://pptr.dev/api/puppeteer.page._) method) and the number of results is less then `reviewsLimit` we click ([`click()`](https://pptr.dev/api/puppeteer.page.click) method) on the next page button element, wait 3 seconds (using [`waitForTimeout`](https://pptr.dev/api/puppeteer.page.waitfortimeout) method), otherwise we stop the loop (using [`break`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break)).

```javascript
while (true) {
  await page.waitForSelector("section[aria-label='Recommended Reviews'] div > ul");
  reviews.push(...(await getReviewsFromPage(page)));
  const isNextPage = await page.$("a[aria-label='Next']");
  if (!isNextPage || reviews.length >= reviewsLimit) break;
  await page.click("a[aria-label='Next']");
  await page.waitForTimeout(3000);
}
```

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

```javascript
await browser.close();

return reviews;
```

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
[
    {
        "user":{
            "name":"Mark T.",
            "link":"https://www.yelp.com/user_details?userid=z44H_fDiNpvH-B8B_vBnBA",
            "thumbnail":"https://s3-media0.fl.yelpcdn.com/photo/9n6QdxRSINg3RZhoy0vw7w/ms.jpg",
            "address":"Seattle, WA",
            "friends":"56",
            "photos":"734",
            "reviews":"241",
            "eliteYear":"Elite 2022"
        },
        "comment":{
            "text":"`This KFC made me sad.  The food: OK.  The To-Go service: NOT GOOD.  They messed up my order, and you might think, \"Check your order before you leave, Mark T.!\"  But they seal the plastic to-go bag with some magical heating method that hermetically seals the bag super well.  Maybe this is good so it won't spill in your car, but it makes it very hard to check the order correctness.  Pro Tip: DO CHECK YOUR ORDER CORRECTNESS.  I mean - I get it - these are hard times and the workers are trying, so Two Yelpy stars instead of One.The vexing part was that the receipt stapled to the outside was completely correct.  It's the contents of the bag that were wrong.  One might reasonably argue that the food is more important than the receipt - particularly when you're hungry for something other than paper.On the plus side the reason I went there was to try the Beyond Chicken nuggets - and they were GOOD!  The taste was good and the texture was good.  I'm not a super chicken connoisseur (thanks spell-check just now), but I've eaten my share of nuggets in my lifetime.  Check out the cross section in the photo.  I'm not sure I could tell it from 'real' chicken.  So anyway, I ordered mashed potatoes with gravy and didn't get the gravy; ordered two types of sauces I didn't get and in general the cole slaw is a total rip at $3.49 for a tiny little container.  If you want people to eat healthy food, don't overcharge for the only green vegetable you sell!`",
            "language":"en"
        },
        "date":"1/28/2022",
        "rating":"2",
        "photos":[
            {
                "link":"https://s3-media0.fl.yelpcdn.com/bphoto/CsgT6CJlTEC9tuqWgw9hLg/180s.jpg",
                "caption":"The Beyond Chicken.  Best when freshly hot."
            },
            {
                "link":"https://s3-media0.fl.yelpcdn.com/bphoto/I_v-WDBLYBTc7z0O8GJCVQ/180s.jpg",
                "caption":"The sadness of my KFC trip."
            },
            {
                "link":"https://s3-media0.fl.yelpcdn.com/bphoto/qMGmBmZPxzD0pQfhfvleJg/180s.jpg",
                "caption":"That texture!  Might even fool chicken-philes!"
            }
        ],
        "feedback":{
            "useful":" 1"
        }
    },
    ...and other results
]
```

<h2 id='serp_api'>Using<a href="https://serpapi.com/yelp-reviews-api"> Yelp Reviews 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/Scrape-Yelp-Reviews-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 reviewsLimit = 50; // hardcoded limit for demonstration purpose

const params = {
  engine: "yelp_reviews", // search engine
  device: "desktop", //Parameter defines the device to use to get the results. It can be set to "desktop" (default), "tablet", or "mobile"
  place_id: "UON0MxZGG0cgsU5LYPjJbg", //Parameter defines the Yelp ID of a place
};

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

const getResults = async () => {
  const reviews = [];
  while (true) {
    const json = await getJson();
    if (json.reviews) {
      reviews.push(...json.reviews);
      params.start ? (params.start += 10) : (params.start = 10);
    } else break;
    if (reviews.length >= reviewsLimit) break;
  }
  return reviews;
};

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 and set how many results we want to receive (`reviewsLimit` constant):

📌Note: you can get place ID from our [Web scraping Yelp Organic Results with Nodejs](https://serpapi.ghost.io/blog/web-scraping-yelp-organic-results-with-nodejs/#full_code) blog post in the SerpApi solution section.

```javascript
const reviewsLimit = 50; // hardcoded limit for demonstration purpose

const params = {
  engine: "yelp_reviews", // search engine
  device: "desktop", //Parameter defines the device to use to get the results. It can be set to "desktop" (default), "tablet", or "mobile"
  place_id: "UON0MxZGG0cgsU5LYPjJbg", //Parameter defines the Yelp ID of a place
};
```

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 need to declare an empty `reviews` array and using [`while`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while) loop get `json`, add `reviews` results from each page and set next page start index (to `params.start` value). If there is no more results on the page or if the number of received results more than `reviewsLimit` we stop the loop (using [`break`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break)) and return `reviews` array:

```javascript
const reviews = [];
while (true) {
  const json = await getJson();
  if (json.reviews) {
    reviews.push(...json.reviews);
    params.start ? (params.start += 10) : (params.start = 10);
  } else break;
  if (reviews.length >= reviewsLimit) break;
}
return reviews;
```

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
[
    {
        "user":{
            "name":"Lesjar M.",
            "user_id":"pQJfTSDC-zEdcrU0K_gONw",
            "link":"https://www.yelp.com/user_details?userid=pQJfTSDC-zEdcrU0K_gONw",
            "thumbnail":"https://s3-media0.fl.yelpcdn.com/photo/k5o32UV20u44mH_W7pPx_A/60s.jpg",
            "address":"Northwest Everett, Everett, WA",
            "photos":1,
            "reviews":2
        },
        "comment":{
            "text":"I just ordered a chicken sandwich and fries. Got it delivered through door dash. The classic chicken sandwich is $8.99 by itself. Which is a decently priced chicken sandwich. When I got the order, and opened the bag. I grabbed the sandwich and I literally thought the driver ate half the sandwich because it was the smallest, pathetic, and sad looking piece of crap, posing as a chicken sandwich I've ever seen. It looked no where near the same size as the picture projected it to be. The picture was a full size chicken sandwich. What was handed to me had to have been an imposter. I'm so angry. I feel like I was totally ripped off. Money is tight, but thought I'd splurge since I'm going back to work tomorrow. I will never eat at KFC again. I've never been so ripped off! (If I could I'd give half a star!)",
            "language":"en"
        },
        "date":"2/8/2022",
        "rating":1,
        "tags":[
            "1 photo"
        ],
        "photos":[
            {
                "link":"https://s3-media0.fl.yelpcdn.com/bphoto/95M1boh80dnsCiBcPbyrAQ/o.jpg",
                "caption":"KFC &#34;Classic Chicken Sandwich.&#34;",
                "uploaded":"February 8, 2022"
            }
        ],
        "feedback":{
            "funny":1,
            "cool":1
        }
    },
  ...and other results
]
```

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

- [Code in the online IDE](https://replit.com/@MikhailZub/Scrape-Yelp-Reviews-with-NodeJS-SerpApi#index.js)
- [Yelp Reviews API](https://serpapi.com/yelp-reviews-api)

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>