Logo Shopify Product Scraper

Shopify Product Scraper

Cộng đồng
liangdabiao
shopify-product-scraper

Thu thập dữ liệu sản phẩm từ các trang thương mại điện tử của thương hiệu và tạo tệp CSV để nhập vào Shopify, kèm URL hình ảnh từ CDN bên ngoài. Dùng khi bạn muốn: (1) thu thập sản phẩm từ URL trang web của một thương hiệu cụ thể, (2) tạo CSV cho Shopify từ dữ liệu sản phẩm, (3) trích xuất hàng loạt thông tin sản phẩm (tiêu đề, giá, SKU, hình ảnh) từ các trang thương mại điện tử, (4) chuyển danh sách sản phẩm trên web sang định dạng nhập vào Shopify. Cụm từ kích hoạt: "scrape products from URL", "抓取产品", "生成Shopify CSV", "批量抓取商品", "抓取XX网站产品", "convert products to Shopify CSV", "extract products from website". Hỗ trợ mọi trang thương mại điện tử. Dùng curl+regex cho các trang SSR, Playwright MCP cho trang hiển thị bằng JS và Firecrawl làm phương án dự phòng.

Tổng quan

Nhà phát hànhliangdabiao
Kho mãfetch-everything
Tên kỹ năngshopify-product-scraper
Sao
50
Bản fork
8
Tệp đi kèm
2
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 2 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được liangdabiao công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Shopify Product Scraper trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/liangdabiao/fetch-everything/tree/main/.claude/skills/shopify-product-scraper
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/liangdabiao/fetch-everything.git /tmp/fetch-everything
mkdir -p .claude/skills
cp -r /tmp/fetch-everything/.claude/skills/shopify-product-scraper .claude/skills/shopify-product-scraper
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Shopify Product Scraper trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Shopify Product Scraper ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Shopify Product Scraper với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Shopify Product Scraper

Scrape product data from brand websites and generate Shopify CSV with remote CDN image URLs (no image downloading needed).

CRITICAL: Windows Python Rule

ALWAYS write Python code to .py files and run with python script.py. NEVER use python -c "..." with multi-line code on Windows — it causes IndentationError: unexpected indent or || goto :error. Only single-line python -c "import json; print(1)" is safe.

Workflow

User provides URL → Assess site → Extract products → Fetch galleries → Generate CSV

Step 0: Assess Target Site

bash
curl -sL -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" \
  "TARGET_URL" -o _page.html --connect-timeout 15 --max-time 30
wc -c _page.html

Check which pattern the site uses (write to a _assess.py file):

python
import re
with open('_page.html', encoding='utf-8') as f:
    html = f.read()

print('data-product:', html.count('data-product'))
print('product-card:', html.count('product-card'))
print('aria-label="Product":', len(re.findall(r'aria-label="[^"]*"[^>]*class="[^"]*product', html)))

jsonlds = re.findall(r'<script type="application/ld\+json">(.*?)</script>', html, re.DOTALL)
import json
types = []
for j in jsonlds:
    d = json.loads(j)
    if isinstance(d, list):
        types.extend([x.get('@type','?') for x in d])
    else:
        types.append(d.get('@type','?'))
print('JSON-LD types:', types)  # BreadcrumbList ≠ Product!
print('Has Product/ItemList:', any(t in ('Product','ItemList') for t in types))

print('__NEXT_DATA__:', html.count('__NEXT_DATA__'))

Pattern decision:

PatternIndicatorsMethod
A: data-* attrsdata-product > 0curl + regex on data attributes
A2: Semantic cardsproduct-card class + aria-labelcurl + regex on article/div
B: JSON-LD Product@type: Product or ItemListcurl + regex on ld+json
C: Next.js__NEXT_DATA__ > 0curl + parse JSON state
D: JS-renderedNone of the abovePlaywright MCP

Important: JSON-LD may exist but only contain BreadcrumbList, not product data. Always check the actual @type.

Step 1: Extract Product List

Pattern A: HTML data-* attributes
python
import re, json

products_raw = re.findall(
    r'<div[^>]*class="[^"]*product[^"]*"[^>]+(data-product-name="[^"]*"[^>]+)>',
    html
)
for attrs_str in products_raw:
    data = dict(re.findall(r'data-([\w-]+)="([^"]*)"', attrs_str))
    # data = {'product_name': '...', 'msrp_price': '...', 'default_id': '...'}
Pattern A2: Semantic HTML cards (Logitech, modern SSR sites)

Many sites use <article> or <div> with class containing "product" and aria-label for the product name:

python
# Example: <article aria-label="MX Keys S" class="product-card ...">
articles = re.findall(
    r'<article[^>]*aria-label="([^"]*)"[^>]*class="[^"]*product-card[^"]*"[^>]*>(.*?)(?=<article[^>]*class="[^"]*product-card|<footer|$)',
    html, re.DOTALL
)
# If aria-label comes after class:
# articles = re.findall(r'<article[^>]*class="[^"]*product-card[^"]*"[^>]*aria-label="([^"]*)"[^>]*>(.*?)...', ...)

for title, card_html in articles:
    url = 'https://example.com' + re.search(r'href="(/[^"]*)"', card_html).group(1)
    image = re.search(r'<img[^>]+src="(https://[^"]+)"', card_html).group(1)
    prices = re.findall(r'\$(\d+\.?\d*)', card_html)  # [sale, msrp] or [price]
    slug = url.split('/')[-1].replace('.html', '')

Key tip: Don't rely on the first aria-label found inside the card — buttons like "Add to wishlist" also have aria-labels. Extract the product name from the <article> tag's own aria-label, not from child elements.

Pattern B: JSON-LD
python
jsonlds = re.findall(r'<script type="application/ld\+json">(.*?)</script>', html, re.DOTALL)
for j in jsonlds:
    d = json.loads(j)
    if isinstance(d, list):
        d = d[0]
    if d.get('@type') in ('Product', 'ItemList'):
        # d['name'], d['offers']['price'], d['image'], d['sku']
Pattern C: Next.js NEXT_DATA
python
m = re.search(r'<script id="__NEXT_DATA__"[^>]*>(.*?)</script>', html, re.DOTALL)
state = json.loads(m.group(1))
products = state['props']['pageProps'].get('products', [])
Pattern D: JS-rendered (use Playwright MCP)
javascript
await (async (page) => {
    await page.goto('TARGET_URL', {timeout: 30000});
    await page.waitForTimeout(3000);
    const products = await page.evaluate(() => {
        const cards = document.querySelectorAll('[class*="product"]');
        return [...cards].map(c => ({
            title: c.querySelector('[class*="title"]')?.textContent?.trim(),
            price: c.querySelector('[class*="price"]')?.textContent?.trim(),
            url: c.querySelector('a')?.href,
            image: c.querySelector('img')?.src,
        })).filter(p => p.title);
    });
    return products;
})(page);

Normalize all extracted products to this intermediate format:

json
[
  {
    "title": "Product Name",
    "description": "Short description",
    "url": "https://example.com/product/slug",
    "category": "category-slug",
    "msrp": "299.99",
    "sale_price": "249.99",
    "compare_price": "299.99",
    "sku": "SKU-001",
    "image": "https://cdn.example.com/main.png",
    "product_slug": "product-slug"
  }
]
  • msrp: The regular/original price. Used as fallback.
  • sale_price: The current selling price (for deals/discount pages).
  • compare_price: The "compare at" / "was" price shown to customer.
  • If no sale, set sale_price = msrp and leave compare_price empty.

Save to {brand}-products.json.

Step 2: Fetch Product Gallery Images

For each product, fetch its detail page to get full image gallery.

IMPORTANT: Use curl via subprocess, not Python urllib. On Windows, Python's urllib has frequent SSL handshake timeouts. curl is more reliable.

Write a _fetch_galleries.py file with this pattern:

python
import re, json, subprocess, time

with open('brand-products.json', encoding='utf-8') as f:
    products = json.load(f)

def fetch_url(url):
    """Use curl subprocess — more reliable than urllib on Windows."""
    try:
        result = subprocess.run(
            ['curl', '-sL', '-A', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
             '--connect-timeout', '15', '--max-time', '30', url],
            capture_output=True, text=True, encoding='utf-8', errors='replace'
        )
        if result.returncode == 0 and len(result.stdout) > 500:
            return result.stdout
    except Exception:
        pass
    return ''

def filter_product_images(urls, product_slug):
    """Keep only images belonging to this specific product."""
    slug_norm = product_slug.replace('-', '').replace('.', '').lower()
    skip = ['swatch', 'icon', 'logo', '/3d/', '-3d', '/ar/', 'diagram',
            'color-ring', 'callout', 'award', 'badge', 'comparison',
            'color-guide', 'video-thumbnail', 'thumbnail', 'icon-']
    seen, result = set(), []
    for url in urls:
        lower = url.lower()
        if not re.search(r'\.(?:png|jpg|jpeg)', lower):
            continue
        if any(s in lower for s in skip):
            continue
        fname = re.search(r'/([^/?]+\.(?:png|jpg|jpeg))', url)
        if fname:
            base = re.sub(r'-\d+x\d+', '', fname.group(1)).split('?')[0].replace('-2x', '')
            if base in seen:
                continue
            seen.add(base)
        # Upgrade resolution
        url = re.sub(r'w_\d+', 'w_1200', url)
        url = re.sub(r'h_\d+', 'h_900', url)
        result.append(url)
    return result[:8]

results = []
for i, p in enumerate(products):
    print(f'[{i+1}/{len(products)}] {p["title"]}')
    html = fetch_url(p['url'])

    if not html:
        # Fallback to listing image only
        results.append({**p, 'gallery': [p['image']] if p.get('image') else []})
        continue

    # Extract all CDN image URLs
    all_imgs = set()
    for m in re.finditer(r'(https://[^"\'>\s]+?\.(?:png|jpg|jpeg))', html):
        all_imgs.add(m.group(1))
    # Also check srcset
    for m in re.finditer(r'(?:srcset|data-src)="([^"]+)"', html):
        for part in m.group(1).split(','):
            u = part.strip().split()[0]
            if re.search(r'\.(?:png|jpg|jpeg)', u):
                all_imgs.add(u)

    gallery = filter_product_images(all_imgs, p['product_slug'])
    if not gallery and p.get('image'):
        gallery = [p['image']]

    results.append({**p, 'gallery': gallery})
    print(f'  Found {len(gallery)} images')

    # Checkpoint every 10 products
    if (i + 1) % 10 == 0:
        with open('brand-products-gallery.json', 'w', encoding='utf-8') as f:
            json.dump(results, f, indent=2, ensure_ascii=False)

    time.sleep(0.5)

with open('brand-products-gallery.json', 'w', encoding='utf-8') as f:
    json.dump(results, f, indent=2, ensure_ascii=False)

Key points for gallery extraction:

  • Filter cross-product images: "YOU MAY ALSO LIKE" sections include other products' images. Filter by product slug.
  • Upgrade image resolution: Replace w_300 → w_1200 etc. in CDN URLs.
  • Deduplicate by filename: Same image at different sizes → keep one.
  • Max 8 images per product.
  • Checkpoint saves: Save progress every 10 products in case of interruption.
  • Slug matching: Use slug_norm with dots and hyphens removed. Some slugs contain version numbers (e.g., mx-keys-s.920-011558) that should be stripped for matching.

Save enriched data as {brand}-products-gallery.json.

Step 3: Generate Shopify CSV

Use the bundled script:

bash
python scripts/gen_shopify_csv.py products-gallery.json --vendor "Brand Name" --output brand_shopify.csv

The script supports these fields:

  • gallery or gallery_images — array of image URLs
  • sale_price — selling price (used as Variant Price)
  • compare_price or msrp — original/compare-at price (used as Variant Compare At Price)
  • image — fallback main image if gallery is empty

Or generate inline following the Shopify CSV format:

Shopify CSV structure (UTF-8 BOM, all fields double-quoted):

Row TypeHandleTitleBody (HTML)Image SrcImage Position
Productproduct-slugProduct Name<p>Description</p>URL1
Image 2product-slugURL2
Image 3product-slugURL3

Key rules:

  • Handle: lowercase + hyphens only (re.sub(r'[^a-z0-9]+', '-', name.lower()))
  • First row: product info + first image
  • Image rows: same Handle, only fill Image Src/Position/Alt Text
  • Images: use remote CDN URLs (Shopify downloads them on import)
  • Max 8 images per product
  • Encoding: utf-8-sig (BOM for Excel compatibility)
  • Quoting: csv.QUOTE_ALL

Required Shopify CSV headers:

Handle, Title, Body (HTML), Vendor, Type, Tags, Published,
Option1 Name, Option1 Value, Variant SKU, Variant Grams,
Variant Inventory Tracker, Variant Inventory Qty,
Variant Inventory Policy, Variant Fulfillment Service,
Variant Price, Variant Compare At Price,
Variant Requires Shipping, Variant Taxable, Variant Barcode,
Image Src, Image Position, Image Alt Text, Gift Card, Variant Image

Step 4: Verify Output

Write a _verify.py file (not inline python):

python
import csv
with open('output.csv', encoding='utf-8-sig') as f:
    rows = list(csv.DictReader(f))
product_rows = [r for r in rows if r['Title']]
image_rows = [r for r in rows if not r['Title']]
print(f'Total rows: {len(rows)}')
print(f'Product rows: {len(product_rows)}')
print(f'Image-only rows: {len(image_rows)}')
for r in product_rows:
    print(f"  {r['Title'][:45]:45s}  ${r['Variant Price']:>8s}  {r['Variant Compare At Price'] and '$'+r['Variant Compare At Price'] or '':>8s}")

Report to user: product count, image count, categories, file location.

Anti-Bot Mitigation

StrategyImplementation
User-Agentcurl -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
Rate limittime.sleep(0.5) between requests; sleep 0.5 in bash
Batch sizeProcess max 20-30 URLs per batch
Timeoutcurl --connect-timeout 15 --max-time 30
SSL issuesUse curl subprocess, not Python urllib
Access DeniedFall back to Playwright MCP with longer delays (3-5s)

Windows Development Notes

  • ALWAYS write Python to .py files — python -c multi-line fails with IndentationError on Windows
  • Use curl subprocess for HTTP fetches, not urllib — avoids SSL handshake timeouts
  • No grep -P on Windows — use grep -o or grep -c (no Perl regex)
  • Use / not \ in Python paths
  • Use project directory for temp files (not /tmp/)
  • CSV encoding: utf-8-sig
  • curl is available natively on Windows 10/11

Troubleshooting

IssueCauseSolution
Empty product listJS-rendered pageUse Playwright MCP (Step 1 Pattern D)
Cross-product images"Recommended" sectionFilter by product slug (Step 2)
404/BlobNotFound imagesCDN variant doesn't existOnly use URLs found in DOM, don't guess
CSV encoding issuesMissing BOMUse utf-8-sig encoding
Price shows as 0Price in JS variableExtract from rendered DOM with Playwright
Duplicate imagesCDN serves same image at different sizesDeduplicate by base filename
SSL timeout on fetchPython urllib unreliable on WindowsUse curl via subprocess (Step 2)
JSON-LD exists but no productsOnly BreadcrumbList, not ProductCheck @type value, try Pattern A2
Wrong aria-label parsedButton aria-labels inside cardsUse article-level aria-label, not child elements
python -c IndentationErrorWindows bash handling of multi-lineWrite to .py file, run with python file.py
grep -oP not workingWindows grep lacks Perl regexUse grep -o or Python regex

References

Tệp đi kèm

Khi kỹ năng đã được tải, mô hình có thể đọc các tệp này nếu cần. Các tệp này chỉ dùng để đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI Shopify Product Scraper làm được gì?

Thu thập dữ liệu sản phẩm từ các trang thương mại điện tử của thương hiệu và tạo tệp CSV để nhập vào Shopify, kèm URL hình ảnh từ CDN bên ngoài. Dùng khi bạn muốn: (1) thu thập sản phẩm từ URL trang web của một thương hiệu cụ thể, (2) tạo CSV cho Shopify từ dữ liệu sản phẩm, (3) trích xuất hàng loạt thông tin sản phẩm (tiêu đề, giá, SKU, hình ảnh) từ các trang thương mại điện tử, (4) chuyển danh sách sản phẩm trên web sang định dạng nhập vào Shopify. Cụm từ kích hoạt: "scrape products from URL", "抓取产品", "生成Shopify CSV", "批量抓取商品", "抓取XX网站产品", "convert products to Shopify CSV", "extract produ...

Vì sao nên dùng Shopify Product Scraper trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Shopify Product Scraper là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Shopify Product Scraper trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/liangdabiao/fetch-everything/tree/main/.claude/skills/shopify-product-scraper. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm rồi cài đặt cả gói dưới dạng một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Shopify Product Scraper?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Shopify Product Scraper với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Shopify Product Scraper với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Shopify Product Scraper có miễn phí không?

Kỹ năng này được liangdabiao phát hành trên GitHub. Hãy xem điều khoản giấy phép trong kho mã. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇