-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
63 lines (45 loc) · 2.01 KB
/
index.js
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
53
54
55
56
57
58
59
60
61
62
63
import fs from 'fs/promises'
import puppeteer from 'puppeteer'
import xlsx from 'xlsx'
const API_KEY = process.env.SCRAPER_API_KEY;
const URL = "https://www.amazon.com/-/es/Laptops/b?ie=UTF8&node=565108";
async function main() {
const response = await fetch(`http://api.scraperapi.com/?api_key=${API_KEY}&url=${URL}&render=true`)
const data = await response.text();
// await fs.writeFile('output.html', data);
// console.log(data);
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.setContent(data)
const productsData = await page.evaluate(() => {
const productsElements = document.querySelectorAll('div.a-section.octopus-pc-asin-info-section')
console.log(productsElements)
const productsData = []
productsElements.forEach(productElement => {
const priceWhole = productElement.querySelector('.a-price-whole');
const priceDecimal = productElement.querySelector('.a-price-fraction')
const price = `${priceWhole.textContent}${priceDecimal.textContent}`
const titleElement = productElement.querySelector('.a-section.octopus-pc-asin-title')
console.log(price, titleElement.textContent)
productsData.push({
price: price,
description: titleElement.textContent.trim() // 'asasd'
})
})
return productsData
})
console.log(productsData)
// write in csv
let csv = 'Description,Price\n'
productsData.forEach(product => {
csv += `${product.description},${product.price}\n`
})
await fs.writeFile('products.csv', csv)
// write in xlsx
const ws = xlsx.utils.json_to_sheet(productsData)
const wb = xlsx.utils.book_new()
xlsx.utils.book_append_sheet(wb, ws, 'Products')
await fs.writeFile('products.xlsx', xlsx.write(wb, { type: 'buffer', bookType: 'xlsx' }))
await browser.close()
}
main()