← back to Handbag Authentication

crawler/chanel-specialist.js

171 lines

const puppeteer = require('puppeteer');

class ChanelSpecialistScraper {
  constructor() {
    this.baseUrl = 'https://auctions.yahoo.co.jp/search/search';

    // Specific Chanel bag models with Japanese names
    this.chanelModels = [
      'シャネル マトラッセ',          // Matelasse/Classic Flap
      'シャネル チェーンショルダー',  // Chain Shoulder
      'シャネル ボーイシャネル',      // Boy Chanel
      'シャネル ガブリエル',          // Gabrielle
      'シャネル 2.55',                // 2.55
      'シャネル トート',              // Tote
      'シャネル デカマトラッセ',      // Jumbo/Maxi
      'シャネル ミニマトラッセ',      // Mini
      'シャネル ココハンドル',        // Coco Handle
      'シャネル バニティ',            // Vanity
      'シャネル チェーントート',      // Chain Tote
      'シャネル カンボン',            // Cambon
      'Chanel Classic Flap',
      'Chanel Boy',
      'Chanel Gabrielle',
      'Chanel 2.55'
    ];

    this.maxPages = 12; // Chanel is very popular
  }

  async scrapeSearch(model, page = 1) {
    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');

      const searchUrl = `${this.baseUrl}?p=${encodeURIComponent(model)}&b=${(page - 1) * 50 + 1}`;
      console.log(`Scraping Chanel specialist: ${searchUrl}`);

      await browserPage.goto(searchUrl, { waitUntil: 'networkidle2', timeout: 30000 });
      await browserPage.waitForSelector('.Product, .Product__item', { timeout: 10000 }).catch(() => {});

      const listings = await browserPage.evaluate(() => {
        const items = [];
        const productElements = document.querySelectorAll('.Product, .Product__item');

        productElements.forEach((item) => {
          try {
            const titleEl = item.querySelector('.Product__title, a');
            const title = titleEl?.textContent?.trim() || '';

            const priceEl = item.querySelector('.Product__price, .u-tax');
            const priceText = priceEl?.textContent?.trim() || '';
            const priceMatch = priceText.match(/[\d,]+/);
            const price = priceMatch ? parseInt(priceMatch[0].replace(/,/g, '')) : 0;

            const imgEl = item.querySelector('img');
            const image = imgEl?.src || '';

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

            const idMatch = url.match(/\/([a-z0-9]+)$/);
            const id = idMatch?.[1] || url;

            const timeEl = item.querySelector('.Product__time');
            const endTime = timeEl?.textContent?.trim() || '';

            // Extract size
            let size = '';
            if (title.match(/ミニ|Mini|Small/i)) size = 'Mini';
            else if (title.match(/スモール|Small/i)) size = 'Small';
            else if (title.match(/ミディアム|Medium|M/i)) size = 'Medium';
            else if (title.match(/ラージ|Large|L/i)) size = 'Large';
            else if (title.match(/マキシ|ジャンボ|デカ|Jumbo|Maxi/i)) size = 'Jumbo/Maxi';

            const sizeNumberMatch = title.match(/(\d+)\s*cm/);
            if (sizeNumberMatch) size = sizeNumberMatch[0];

            // Extract material
            let material = '';
            if (title.match(/ラムスキン|Lambskin/i)) material = 'Lambskin';
            else if (title.match(/キャビアスキン|Caviar/i)) material = 'Caviar';
            else if (title.match(/カーフ|Calfskin/i)) material = 'Calfskin';
            else if (title.match(/エナメル|Patent/i)) material = 'Patent';
            else if (title.match(/キャンバス|Canvas/i)) material = 'Canvas';
            else if (title.match(/ツイード|Tweed/i)) material = 'Tweed';

            // Extract color
            const colorMatch = title.match(/(ブラック|ホワイト|レッド|ブルー|グリーン|ピンク|ベージュ|ネイビー|ゴールド|シルバー|Black|White|Red|Blue|Green|Pink|Beige|Navy|Gold|Silver)/i);
            const color = colorMatch ? colorMatch[1] : '';

            // Detect condition
            let condition = 'Used';
            if (title.match(/未使用|新品|UNUSED|NEW/i)) {
              condition = 'New/Unused';
            } else if (title.match(/美品|極美品|EXCELLENT/i)) {
              condition = 'Excellent';
            } else if (title.match(/良品|GOOD/i)) {
              condition = 'Good';
            } else if (title.match(/難あり|ジャンク|JUNK|DAMAGED/i)) {
              condition = 'Fair/Damaged';
            }

            if (title && price > 0) {
              items.push({
                external_id: id,
                title,
                price_jpy: price,
                image_url: image,
                thumbnail_url: image,
                product_url: url,
                listing_type: 'auction',
                auction_end_date: endTime,
                condition,
                size,
                color,
                material
              });
            }
          } catch (e) {
            console.error('Error parsing Chanel item:', e);
          }
        });

        return items;
      });

      await browser.close();
      return listings;

    } catch (error) {
      console.error(`Error scraping Chanel specialist:`, error.message);
      return [];
    }
  }

  async scrapeAllModels() {
    const allListings = [];

    for (const model of this.chanelModels) {
      console.log(`\nScraping Chanel specialist for ${model}...`);

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

        if (listings.length === 0) break;

        listings.forEach(listing => {
          listing.brand = 'Chanel';
          listing.source = 'yahoo_chanel_specialist';
          listing.model = model;
        });

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

        await new Promise(resolve => setTimeout(resolve, 3500));
      }
    }

    console.log(`\n✨ Chanel specialist crawl complete: ${allListings.length} total items`);
    return allListings;
  }
}

module.exports = ChanelSpecialistScraper;