当前位置: 首页 > Skill >

Auto Scraping to CSV

Auto Scraping to CSV

Auto Scraping to CSV

使用基于文本的 DOM 操作抓取任意网页,并将结构化数据导出为 CSV。该代理处理复杂页面细节——无限滚动、分页等。

1.0.1 2026.11.22 948
获取Skill文件查看使用说明
作 者:周宁 许可证: 更新时间:2026.11.22
本文目录展开

Auto Scraping to CSV — Agent-Driven Web Scraping

Scrape any webpage using text-based DOM manipulation and export structured data to CSV. The agent handles complex page nuances — infinite scroll, pagination, popups, lazy loading — and asks clarifying questions when data is ambiguous. No external LLM required.

Philosophy: Let the Agent Figure It Out

Traditional scraping requires you to inspect HTML, write CSS selectors, handle edge cases, and debug when the site changes. This skill flips that:

You say what you want. The agent handles the how.

You: "Scrape product catalog"
Agent: "I see 50 products across 5 pages with infinite scroll. 
        I also see 'Price', 'Sale Price', and 'Member Price' columns.
        Which price field should I extract?"
You: "Sale Price"
Agent: [handles scrolling, pagination, extracts 50 rows] → products.csv

The agent will:

  1. Explore the page structure via text-based DOM
  2. Detect complexity — scroll, pagination, tabs, filters
  3. Ask questions when ambiguous (multiple price fields, missing data, format choices)
  4. Handle edge cases — dismiss popups, wait for lazy loading, retry on errors
  5. Export CSV — clean, structured, ready to use

When to Use

  • Product catalogs: "Scrape all laptops with prices and ratings"
  • News/articles: "Get latest blog posts with titles, dates, authors"
  • Directory listings: "Extract all company names, emails, and websites"
  • Table data: "Get the pricing table from this SaaS page"
  • Real estate: "Scrape listings with price, beds, baths, square footage"
  • Job boards: "Get job titles, companies, locations, and salary ranges"
  • Social feeds: "Extract posts with engagement counts (likes, comments, shares)"
  • Research data: "Get citation counts, authors, publication dates from this index"

How It Works

Claude (Host Model)
    ↕  HTTP
Bridge Server (Node.js + Playwright)
    ↕  page.evaluate()
Browser (Chromium) ← Page-Agent injected
  1. Bridge launches a local Chromium browser via Playwright
  2. Page-Agent is injected as an IIFE script from CDN into the target page
  3. Page-Agent indexes the DOM and generates a simplified text representation:
    [5]<a >Widget Pro Laptop /></a>
    [12]<div >$1,299.99 /></div>
    [18]<div >4.5 stars (128 reviews) /></div>
    
  4. Claude receives the text state, understands the page structure, decides actions
  5. Agent asks questions when data is ambiguous or complex
  6. Loop continues until all data is extracted or user says stop
  7. CSV export converts structured JSON to CSV

First-Time Setup

1. Install Playwright

npm install -D playwright
npx playwright install chromium

2. Place the Bridge Script

# Copy from this skill folder to your agents directory
cp .claude/skills/auto-scraping-to-csv/page-agent-bridge.mjs .claude/agents/

3. Start the Bridge

node .claude/agents/page-agent-bridge.mjs

Default port: 9876.

4. Verify Health

curl http://localhost:9876/health

Agent-Driven Scraping Workflow

Step 1: Request What You Want

/scrape-to-csv https://example.com/products
  "Extract all products with name, price, rating, and number of reviews"

Step 2: Agent Explores and Asks Questions

The agent will fetch the DOM state and may ask:

Agent: "I found 24 products on the current page. The site has infinite scroll 
        and I can see more products loading as I scroll. 
        How many products do you want total? (type 'all' for everything)"
You: "50"

Agent: "I see three price fields:
        - Original Price: $1,299
        - Sale Price: $999
        - Member Price: $899
        Which one should I extract?"
You: "Sale Price"

Agent: "Some products are out of stock and show 'N/A' for price.
        Should I:
        A) Include them with 'N/A'
        B) Skip those rows
        C) Mark as 'Out of Stock' in a separate column"
You: "C"

Step 3: Agent Handles Complexity

The agent automatically:

  • Scrolls to load more content
  • Clicks pagination buttons
  • Waits for lazy-loaded images/data
  • Dismisses cookie banners and popups
  • Retries if elements are slow to appear
  • Stops gracefully if the site blocks scraping

Step 4: Preview and Confirm

Agent: "Extracted 50 products. Here's a preview:

| name | price | rating | reviews | stock_status |
|------|-------|--------|---------|-------------|
| Widget Pro | $999 | 4.5 | 128 | In Stock |
| Gadget Mini | $499 | 4.2 | 89 | In Stock |
| ... | ... | ... | ... | ... |

Save as 'products.csv'? (yes/no/change columns)"
You: "yes"

Step 5: CSV Delivered

Agent: "Saved to ./products.csv — 50 rows, 5 columns"

Handling Complex Scenarios

Infinite Scroll

You: "Scrape all posts from this feed"
Agent: "The page loads 10 posts at a time via infinite scroll.
        I've scrolled 3 times and found 30 posts so far.
        Should I continue scrolling? (yes/no/scroll N more times)"
You: "scroll 5 more times"
Agent: [scrolls] → "Found 80 total posts. Saved to feed.csv"

Pagination

You: "Get all products from this catalog"
Agent: "I see pagination: Page 1 of 12. 
        I can scrape all 12 pages (may take 2-3 minutes) or a subset.
        How many pages?"
You: "all"
Agent: [clicks through 12 pages] → "360 products saved to catalog.csv"

Login Required

You: "Scrape my order history"
Agent: "The page redirects to a login screen. 
        I need credentials to proceed.
        Please provide:
        - Username/email
        - Password
        Or type 'skip' to abort."
You: "skip"
Agent: "Aborted. No data extracted."

Multiple Data Formats

You: "Get prices from this page"
Agent: "I found prices in multiple formats:
        - '$19.99' (US format)
        - '€17.99' (EU format)
        - '¥2,980' (JP format)
        Which format should I standardize to?"
You: "Keep as-is, add a 'currency' column"
Agent: [extracts with currency detection] → prices.csv

Missing / Inconsistent Data

You: "Extract employee data from this directory"
Agent: "I see 100 employee cards. Some are missing:
        - 12 missing phone numbers
        - 8 missing job titles
        - 3 missing photos
        How should I handle missing fields?
        A) Leave blank
        B) Fill with 'N/A'
        C) Skip those rows entirely"
You: "B"
Agent: [extracts 100 rows with 'N/A' for missing fields] → employees.csv

Natural Language Commands

/scrape-to-csv <url> <description>

General scraping with CSV export.

/scrape-to-csv https://news.ycombinator.com
  "Get top 30 stories with title, URL, points, and comment counts"

/scrape-to-csv https://www.anthropic.com/news
  "Latest blog posts: title, date, category, URL"

/scrape-to-csv https://example.com/realestate
  "Listings: address, price, beds, baths, sqft, listing agent"

/scrape-table <url> <selector_or_description>

Extract a specific table.

/scrape-table https://example.com/pricing
  "The comparison table with Basic/Pro/Enterprise columns"

/scrape-table https://example.com/sales
  "Q4 2024 revenue breakdown table"

/scrape-news <url>

Optimized for news/blog scraping.

/scrape-news https://techcrunch.com
  "Latest 20 articles: title, author, date, excerpt, URL"

/scrape-news https://blog.openai.com
  "All posts from 2024: title, date, tags, URL"

/scrape-products <url>

Optimized for e-commerce.

/scrape-products https://amazon.com/s?k=laptops
  "Laptops: name, brand, price, rating, prime eligible, URL"

/scrape-products https://shopify-store.com/collections/all
  "All products: name, price, compare-at price, availability"

Output Format

The agent produces a structured markdown report:

## Scraping Report — example.com/products
**Session:** a1b2c3d4 | **Duration:** 2m 14s | **Rows:** 50

### Task
Extract all products with name, price, rating, and number of reviews

### Agent Decisions
- **Pagination**: Detected infinite scroll, scrolled 5 times
- **Price field**: Chose "Sale Price" per user request
- **Missing data**: Filled out-of-stock prices with "N/A" per user request
- **Columns**: name, sale_price, rating, review_count, stock_status

### Sample Data

| name | sale_price | rating | review_count | stock_status |
|------|-----------|--------|-------------|-------------|
| Widget Pro | $999 | 4.5 | 128 | In Stock |
| Gadget Mini | $499 | 4.2 | 89 | In Stock |
| Super Gizmo | $1,299 | 4.8 | 256 | Out of Stock |

### File
`./products.csv` — 50 rows, 5 columns

CSV Conversion Options

Option A — Python (recommended)

import json, csv, re

# Bridge returns: "✅ Executed JavaScript. Result: [{...}, {...}]"
msg = """PASTE_BRIDGE_RESPONSE_HERE"""
match = re.search(r'Result: ([.*])', msg)
if match:
    data = json.loads(match.group(1))
    with open('output.csv', 'w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=data[0].keys())
        writer.writeheader()
        writer.writerows(data)
    print(f"Wrote {len(data)} rows to output.csv")

Option B — Node.js

const fs = require('fs');
const data = JSON.parse(fs.readFileSync('data.json', 'utf8'));
const headers = Object.keys(data[0]);
const csv = [
  headers.join(','),
  ...data.map(row => headers.map(h => `"${(row[h]||'').replace(/"/g,'""')}"`).join(','))
].join('n');
fs.writeFileSync('output.csv', csv);

Troubleshooting

Bridge won't start

Error: Cannot find module 'playwright'

Fix: npm install -D playwright && npx playwright install chromium

Site blocks scraping

Agent detects: "The site returned 403 Forbidden. This may be bot protection." Options:

  • Try headless: false (looks more like a real user)
  • Add delays between requests
  • Use a different user agent

Page loads but no data found

Agent detects: "The page loaded but I see mostly navigation elements. Content may be behind a login or loaded dynamically." Agent asks: "Should I wait longer, scroll down, or do you have login credentials?"

Data looks wrong

Agent detects: "Prices show as 'NaN' or empty. The site may use JavaScript to render prices." Agent asks: "Should I try executing JavaScript to extract the real values, or skip this field?"

Comparison with Other Tools

Tool Setup Selectors Complex Pages Agent Questions Best For
Auto Scraping to CSV npm install None needed Handles automatically Yes, clarifies ambiguity One-off extraction, exploratory scraping
BeautifulSoup pip install Required Manual handling No Known structure, repeated scraping
Scrapy Project setup Required Middleware needed No Large-scale crawling, pipelines
Playwright E2E npm install Required Manual handling No Testing, automation
Browser-Use API key None Partial Limited Multi-page research

Use this skill when:

  • You want to scrape without writing selectors
  • The page structure is complex or unknown
  • You need the agent to handle edge cases (scroll, popups, pagination)
  • You want clarifying questions when data is ambiguous
  • You need quick one-off extraction to CSV

Bridge API Reference

POST /sessions

Launch a new browser session.

Body:

{ "url": "https://example.com", "headless": false }

Response: { "id": "abc123", "url": "https://example.com" }

GET /sessions/:id/state

Get text-based DOM state.

Response: { url, title, header, content, footer }

POST /sessions/:id/act

Execute an action.

Body:

{ "action": "executeJavascript", "params": { "script": "return document.title;" } }

DELETE /sessions/:id

Close session.

POST /shutdown

Stop bridge.

Skill: auto-scraping-to-csv v1.0.0 | Bridge: page-agent-bridge.mjs | Powered by Alibaba Page-Agent + Playwright

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,034
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,018
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,017
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,013
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,013
Skill 文件
  • SKILL.md
    • Auto Scraping to CSV — Agent-Driven Web Scraping
    • Philosophy: Let the Agent Figure It Out
    • When to Use
    • How It Works
    • First-Time Setup
      • 1. Install Playwright
      • 2. Place the Bridge Script
      • 3. Start the Bridge
      • 4. Verify Health
    • Agent-Driven Scraping Workflow
      • Step 1: Request What You Want
      • Step 2: Agent Explores and Asks Questions
      • Step 3: Agent Handles Complexity
      • Step 4: Preview and Confirm
      • Step 5: CSV Delivered
    • Handling Complex Scenarios
      • Infinite Scroll
      • Pagination
      • Login Required
      • Multiple Data Formats
      • Missing / Inconsistent Data
    • Natural Language Commands
      • /scrape-to-csv <url> <description>
      • /scrape-table <url> <selector_or_description>
      • /scrape-news <url>
      • /scrape-products <url>
    • Output Format
    • CSV Conversion Options
      • Option A — Python (recommended)
      • Option B — Node.js
    • Troubleshooting
      • Bridge won't start
      • Site blocks scraping
      • Page loads but no data found
      • Data looks wrong
    • Comparison with Other Tools
    • Bridge API Reference
      • POST /sessions
      • GET /sessions/:id/state
      • POST /sessions/:id/act
      • DELETE /sessions/:id
      • POST /shutdown
  • 项目或源文件

相关 Skill

更多
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...
音频混音工具 音频混音工具 名称:Sound Mixing Tool(标识 sound-mixing-tool) 短简介(≤60字):音乐/音效响度精确对齐 + 融合混音工作流:用 ffmpeg 两段式 loudnorm 把多组素材 LUFS 偏差压到 <0.10,再最小干预融合、导出可进引擎的独立分轨。 标签/关键词:音频混音 响度匹配 LUFS ffmpeg 游戏音频 音效设计 Wwise FMOD 分轨导出 后期处理 触发词:混音 · 响度匹配 · LUFS 对齐 · MIX 版本 · 音乐音效分轨 · 融合 · 不打架 · 不能盖住 适用场景 :游戏音频集成、影视短视频配乐、播客后期