-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
52 lines (41 loc) · 1.69 KB
/
Copy pathindex.js
File metadata and controls
52 lines (41 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import puppeteer from 'puppeteer';
async function getQuotes() {
const browser = await puppeteer.launch({
headless: false,
});
const page = await browser.newPage();
try {
await page.goto('http://quotes.toscrape.com/', {
waitUntil: 'domcontentloaded',
});
const allQuotes = [];
while (true) {
const quotesOnPage = await page.evaluate(() => {
const quotelist = document.querySelectorAll('.quote');
return Array.from(quotelist).map((quote) => {
const textElement = quote.querySelector('.text');
const authorElement = quote.querySelector('.author');
const tagsElement = quote.querySelector('.tag');
const text = textElement ? textElement.innerHTML : '';
const author = authorElement ? authorElement.innerHTML : '';
const tags = tagsElement ? tagsElement.innerHTML : '';
return { text, author, tags };
});
});
allQuotes.push(...quotesOnPage);
const nextButton = await page.$('.pager > .next > a');
if (nextButton) {
await nextButton.click();
await page.waitForTimeout(1000); // Add a delay to ensure the next page is loaded
} else {
break; // Exit the loop if there is no "Next" button
}
}
return allQuotes;
} catch (error) {
console.error('Error in getQuotes:', error);
throw error; // Rethrow the error for handling in the calling function
} finally {
await browser.close();
}
}