js wait for seconds 1

js wait for seconds

  setTimeout(function(){ 
    console.log("Ready")
}, 1000);

Here is what the above code is Doing:
1. We’re creating a new variable called `browser` and assigning it to a new instance of the `puppeteer` library.
2. We’re telling the `browser` to open a new page.
3. We’re telling the `page` to navigate to the `https://www.google.com` URL.
4. We’re telling the `page` to wait for 1 second.
5. We’re telling the `page` to print the text “Ready” to the console.

Now, let’s run the code.

“`
node index.js
“`

You should see the following output:

“`
Ready
“`

## Scraping the Data

Now that we have a working browser, let’s start scraping the data.

First, let’s navigate to the `https://www.google.com/search?q=puppeteer` URL.

“`
await page.goto(‘https://www.google.com/search?q=puppeteer’);
“`

Next, let’s wait for the page to load.

“`
await page.waitFor(1000);
“`

Now, let’s get the HTML of the page.

“`
const html = await page.content();
“`

Finally, let’s print the HTML to the console.

“`
console.log(html);
“`

Here’s what the final code should look like:

“`
const puppeteer = require(‘puppeteer’);

(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(‘https://www.google.com/search?q=puppeteer’);
await page.waitFor(1000);
const html = await page.content();
console.log(html);
await browser.close();
})();
“`

Now, let’s run the code.

“`
node index.js
“`

You should see the HTML of the page printed to the console.

## Extracting the Data

Now that we have the HTML of the page, let’s extract the data we want.

First, let’s install the `cheerio` library.

“`
npm install cheerio
“`

Next, let’s require the `cheerio` library.

“`
const cheerio = require(‘cheerio’);
“`

Now, let’s load the HTML into `cheerio`.

“`
const $ = cheerio.load(html);
“`

Finally, let’s extract the data we want.

“`
const data = [];
$(‘.g’).each(function() {
const title = $(this).find(‘.r’).text();
const link = $(this).find(‘.r a’).attr(‘href’);
data.push({ title, link });
});
“`

Here’s what the final code should look like:

“`
const puppeteer = require(‘puppeteer’);
const cheerio = require(‘cheerio’);

(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(‘https://www.google.com/search?q=puppeteer’);
await page.waitFor(1000);
const html = await page.content();

Similar Posts