← back to Handbag Authentication

crawler/rakuten-global.js

132 lines

const puppeteer = require('puppeteer');

class RakutenGlobalScraper {
  constructor() {
    this.baseUrl = 'https://global.rakuten.com/en/search/';
    this.brands = ['Gucci', 'Louis Vuitton', 'Chanel', 'Hermes', 'Prada', 'Dior', 'Fendi', 'Balenciaga', 'Celine', 'Bottega Veneta'];
    this.maxPages = 3;
  }

  async scrapeSearch(brand, page = 1) {
    const searchUrl = `${this.baseUrl}?k=${encodeURIComponent(brand + ' bag')}&p=${page}`;

    try {
      const browser = await puppeteer.launch({
        headless: 'new',
        args: ['--no-sandbox', '--disable-setuid-sandbox']
      });

      const browserPage = await browser.newPage();
      await browserPage.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');

      console.log(`Scraping Rakuten Global: ${searchUrl}`);
      await browserPage.goto(searchUrl, { waitUntil: 'networkidle2', timeout: 30000 });

      // Wait for products to load
      await browserPage.waitForSelector('.search-result-item, .item, [data-item-id]', { timeout: 10000 }).catch(() => {});

      const listings = await browserPage.evaluate(() => {
        const items = [];
        const productSelectors = [
          '.search-result-item',
          '.item-card',
          '.product-item',
          '[data-item-id]'
        ];

        let productElements = [];
        for (const selector of productSelectors) {
          productElements = document.querySelectorAll(selector);
          if (productElements.length > 0) break;
        }

        productElements.forEach((item) => {
          try {
            // Extract image
            const imgEl = item.querySelector('img');
            const image = imgEl?.src || imgEl?.dataset?.src || '';

            // Extract title
            const titleEl = item.querySelector('.item-name, .product-title, h3, a[title]');
            const title = titleEl?.textContent?.trim() || titleEl?.getAttribute('title') || '';

            // Extract price - Rakuten shows JPY
            const priceEl = item.querySelector('.price, [class*="price"]');
            const priceText = priceEl?.textContent?.trim() || '';
            const priceMatch = priceText.match(/[\d,]+/);
            const priceJPY = priceMatch ? parseInt(priceMatch[0].replace(/,/g, '')) : 0;

            // Extract URL
            const linkEl = item.querySelector('a');
            const url = linkEl?.href || '';

            // Extract ID
            const id = item.dataset?.itemId || url.split('/').pop() || url;

            // Extract condition (most Rakuten items are new or used)
            const conditionEl = item.querySelector('.condition, [class*="condition"]');
            const condition = conditionEl?.textContent?.trim() || 'Used';

            if (title && priceJPY > 0) {
              items.push({
                external_id: id,
                title,
                price_jpy: priceJPY,
                image_url: image,
                thumbnail_url: image,
                product_url: url.startsWith('http') ? url : `https://global.rakuten.com${url}`,
                condition,
                listing_type: 'buy'
              });
            }
          } catch (e) {
            console.error('Error parsing Rakuten item:', e);
          }
        });

        return items;
      });

      await browser.close();
      return listings;

    } catch (error) {
      console.error(`Error scraping Rakuten Global page ${page}:`, error.message);
      return [];
    }
  }

  async scrapeAllBrands() {
    const allListings = [];

    for (const brand of this.brands) {
      console.log(`\nScraping Rakuten Global for ${brand}...`);

      for (let page = 1; page <= this.maxPages; page++) {
        const listings = await this.scrapeSearch(brand, page);

        if (listings.length === 0) {
          console.log(`No more results for ${brand} at page ${page}`);
          break;
        }

        // Add brand and source info
        listings.forEach(listing => {
          listing.brand = brand;
          listing.source = 'rakuten_global';
        });

        allListings.push(...listings);
        console.log(`Found ${listings.length} items on page ${page}`);

        // Rate limiting
        await new Promise(resolve => setTimeout(resolve, 3000 + Math.random() * 2000));
      }
    }

    return allListings;
  }
}

module.exports = RakutenGlobalScraper;