From 8e6c8c55115b74733fae598ce7fcc26becd6e127 Mon Sep 17 00:00:00 2001 From: Leon Xu Date: Sat, 30 Dec 2023 13:16:16 -0800 Subject: [PATCH] file & doc: create and update the scraper index file --- lib/scraper/index.ts | 82 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 lib/scraper/index.ts diff --git a/lib/scraper/index.ts b/lib/scraper/index.ts new file mode 100644 index 0000000..36305e3 --- /dev/null +++ b/lib/scraper/index.ts @@ -0,0 +1,82 @@ +import axios from 'axios'; +import * as cheerio from 'cheerio'; +import { extractPrice, extractCurrency } from '../utils'; + +export async function scrapeAmazonProduct(url: string) { + if (!url) return; + + // BringData proxy configuration + const username = String(process.env.BRIGHT_DATA_USERNAME); + const password = String(process.env.BRIGHT_DATA_USERNAME); + const port = 22225 + const session_id = (1000000 * Math.random()) | 0; + const options = { + auth: { + username: `${username}-session-${session_id}`, + password, + }, + host: 'brd.superproxy.io', + port, + rejectUnauthorized: false + } + + try { + // Fetch the product page + const response = await axios.get(url, options); + const $ = cheerio.load(response.data); + + // Extract the product title + const title = $('#productTitle').text().trim(); + const currentPrice = extractPrice( + $('.priceToPay span.a-price-whole'), + $('a.size.base.a-color-price'), + $('.a-button-selected .a-color-base'), + $('.a-price.a-text-price') + ); + + const originalPrice = extractPrice( + $('#priceblock_ourprice'), + $('.a-price.a-text-price span.a-offscreen'), + $('#listPrice'), + $('#priceblock_dealprice'), + $('.a-size-base.a-color-price') + ); + + const outOfStock = $('#availability span').text().trim().toLowerCase() === 'currently unavailable'; + + const images = + $('#imgBlkFront').attr('data-a-dynamic-image') || + $('#landingImage').attr('data-a-dynamic-image') || + '{}' + + const imageUrls = Object.keys(JSON.parse(images)); + + const currency = extractCurrency($('.a-price-symbol')); + + const discountRate = $('.savingsPercentage').text().replace(/[-%]/g, ""); + + // Construct data object with scraped information + const data = { + url, + currency: currency || '$', + image: imageUrls[0], + title, + currentPrice: Number(currentPrice) || Number(originalPrice), + originalPrice: Number(originalPrice) || Number(currentPrice), + priceHistory: [], + discountRate: Number(discountRate), + category: 'category', + reviewsCount:100, + stars: 4.5, + isOutOfStock: outOfStock, + lowestPrice: Number(currentPrice) || Number(originalPrice), + highestPrice: Number(originalPrice) || Number(currentPrice), + averagePrice: Number(currentPrice) || Number(originalPrice), + } + + console.log(data); + + } catch (error: any) { + throw new Error(`Failed to scrape product ${error.message}`); + } +} \ No newline at end of file