📡 数据采集基础

另类数据因子挖掘 · 实战
🔌 API 调用 🕷️ 网络爬虫入门 ⚙️ Requests / Scrapy ⚖️ 伦理与合规

🌟 从零构建另类数据采集管线:API 请求、爬虫框架、以及数据伦理红线。中小学生色系 · 快乐学习!

🔗 API 调用

  • RESTful 风格:GET / POST / 鉴权
  • 常见数据格式:JSON, XML, CSV
  • 限流 & 重试:429 处理
  • API Key 管理 & 环境变量

📦 示例:Binance 行情

import requests
url = "https://api.binance.com/api/v3/ticker/price"
params = {"symbol": "BTCUSDT"}
resp = requests.get(url, params=params)
data = resp.json()
print(f"BTC 价格: {data['price']}")

🕸️ 爬虫入门

  • Requests 库:HTTP 会话、headers、cookies
  • Scrapy 框架:Spider, Item Pipeline, 中间件
  • HTML 解析:BeautifulSoup / lxml
  • 动态渲染:Selenium / Playwright

🧪 小试牛刀

import requests
from bs4 import BeautifulSoup

url = "https://example.com/data"
r = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
soup = BeautifulSoup(r.text, "html.parser")
for item in soup.select(".data-row"):
    print(item.get_text(strip=True))

⚖️ 伦理 & 合规

  • ROBOTS 遵守 robots.txt
  • GDPR 个人数据保护
  • 版权 数据库权利 & 条款
  • 频率 礼貌爬取 & 限速
  • 透明 声明数据用途

📜 检查清单

  1. 查看网站 Terms of Service
  2. 设置合理的 Crawl-delay
  3. 不采集非公开/登录后数据
  4. 数据脱敏 & 匿名化
特性Requests + BeautifulSoupScrapy 框架
上手难度⭐ 低 (适合快速原型)⭐⭐⭐ 中高 (结构完善)
并发/异步需自行实现 (ThreadPool)内置异步 Twisted, 高性能
中间件/扩展无丰富的中间件、Pipeline、扩展
数据去重手动内置去重 (RFPDupeFilter)
适用场景小规模、单页面、API 调试大规模、多页面、生产级爬虫
🌐 数据源 Web / API 🕷️ 采集引擎 Requests / Scrapy 🧹 解析 & 清洗 BeautifulSoup / lxml 📊 另类因子 存储 / 特征 🤖 robots.txt ⏱️ 限速 / 重试 / 鉴权 🔒 脱敏 / 匿名化 📋 合规审查 ⬆️ 伦理与合规贯穿全流程 ⬆️

🕸️ Scrapy Spider 示例 另类数据 · 新闻情绪

# news_spider.py
import scrapy

class NewsSpider(scrapy.Spider):
    name = "financial_news"
    start_urls = ["https://example-finance-news.com/latest"]

    def parse(self, response):
        for article in response.css("div.news-item"):
            yield {
                "title": article.css("h2::text").get(),
                "date": article.css("span.date::text").get(),
                "sentiment": self.estimate_sentiment(article.css("p::text").get())
            }
        next_page = response.css("a.next::attr(href)").get()
        if next_page:
            yield scrapy.Request(url=next_page, callback=self.parse)

🧑‍⚖️ 数据采集伦理 · 黄金法则

  • 尊重版权 & 数据库权利
  • 绝不采集个人隐私数据
  • 设置合理的 User-Agent
  • 遵守 robots.txt 及 Crawl-delay
  • 数据仅用于学术/研究/量化因子
  • 公开数据源 & 注明出处